code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -0,0 +1,36 @@ +package com.doubleowner.revibe.global.common.service; + +import com.doubleowner.revibe.global.exception.CommonException; +import com.doubleowner.revibe.global.exception.errorCode.ErrorCode; +import com.doubleowner.revibe.global.util.S3Uploader; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; + +@Service +@RequiredArgsConstructor +public class ImageService { + private final S3Uploader s3Uploader; + + public String UploadImage(String image, MultipartFile file) { + try { + if (image != null) { + s3Uploader.deleteImage(image); + } + return s3Uploader.upload(file); + } catch (IOException e) { + throw new CommonException(ErrorCode.FAILED_UPLOAD_IMAGE); + } + } + + public void deleteImage(String image) { + try { + s3Uploader.deleteImage(image); + } catch (IOException e) { + throw new CommonException(ErrorCode.FAILED_DELETE_IMAGE); + } + } + +}
Java
_:hammer_and_wrench: Refactor suggestion_ **์ด๋ฏธ์ง€ ๊ฒฝ๋กœ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค** `image` ํŒŒ๋ผ๋ฏธํ„ฐ์— ๋Œ€ํ•œ null ์ฒดํฌ์™€ ๊ฒฝ๋กœ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ๊ฐ€ ๋ˆ„๋ฝ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. ์ž˜๋ชป๋œ ์ด๋ฏธ์ง€ ๊ฒฝ๋กœ๋กœ ์ธํ•œ ๋ถˆํ•„์š”ํ•œ S3 ํ˜ธ์ถœ์„ ๋ฐฉ์ง€ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ˆ˜์ •ํ•˜๋Š” ๊ฒƒ์„ ์ œ์•ˆํ•ฉ๋‹ˆ๋‹ค: ```diff public void deleteImage(String image) { + if (image == null || image.trim().isEmpty()) { + return; + } try { s3Uploader.deleteImage(image); } catch (IOException e) { ``` <!-- suggestion_start --> <details> <summary>๐Ÿ“ Committable suggestion</summary> > โ€ผ๏ธ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. `````suggestion public void deleteImage(String image) { if (image == null || image.trim().isEmpty()) { return; } try { s3Uploader.deleteImage(image); } catch (IOException e) { throw new CommonException(ErrorCode.FAILED_DELETE_IMAGE); } } ````` </details> <!-- suggestion_end --> <!-- This is an auto-generated comment by CodeRabbit -->
@@ -2,25 +2,25 @@ import com.doubleowner.revibe.domain.execution.entity.Execution; import com.doubleowner.revibe.domain.execution.repository.ExecutionRepository; +import com.doubleowner.revibe.domain.point.PointService; import com.doubleowner.revibe.domain.review.dto.ReviewRequestDto; import com.doubleowner.revibe.domain.review.dto.ReviewResponseDto; import com.doubleowner.revibe.domain.review.dto.UpdateReviewRequestDto; import com.doubleowner.revibe.domain.review.entity.Review; import com.doubleowner.revibe.domain.review.repository.ReviewRepository; import com.doubleowner.revibe.domain.user.entity.User; -import com.doubleowner.revibe.domain.user.repository.UserRepository; +import com.doubleowner.revibe.global.common.service.ImageService; import com.doubleowner.revibe.global.config.auth.UserDetailsImpl; import com.doubleowner.revibe.global.exception.CommonException; import com.doubleowner.revibe.global.exception.errorCode.ErrorCode; -import com.doubleowner.revibe.global.util.S3Uploader; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Slice; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; -import java.io.IOException; import java.util.List; @@ -29,26 +29,21 @@ public class ReviewService { private final ReviewRepository reviewRepository; private final ExecutionRepository executionRepository; - private final UserRepository userRepository; - private final S3Uploader s3Uploader; + private final PointService pointService; + private final ImageService imageService; - private static final int TEXT_ONLY_POINT = 100; - private static final int TEXT_IMAGE_POINT = 500; - private static final int DIFFERENCE_POINT = 400; @Transactional public ReviewResponseDto write(ReviewRequestDto reviewRequestDto, User user) { - Execution execution = executionRepository.findExecutionById(reviewRequestDto.getPaymentId(), user.getEmail()) .orElseThrow(() -> new CommonException(ErrorCode.NOT_FOUND_VALUE, "๋‚ด์—ญ์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค")); + String image = null; - int point = TEXT_ONLY_POINT; - if (reviewRequestDto.getImage() != null) { - image = uploadImage(reviewRequestDto.getImage()); - point = TEXT_IMAGE_POINT; - } + if (hasImage(reviewRequestDto.getImage())) { + image = imageService.UploadImage(image, reviewRequestDto.getImage()); + } Review review = Review.builder() .starRate(reviewRequestDto.getStarRate()) @@ -60,12 +55,11 @@ public ReviewResponseDto write(ReviewRequestDto reviewRequestDto, User user) { .user(user) .build(); - Review save = reviewRepository.save(review); - user.addPoint(point); - userRepository.save(user); + Review savedReview = reviewRepository.save(review); + pointService.addReviewPoint(user, image); - return toDto(save); + return toDto(savedReview); } @@ -76,49 +70,42 @@ public List<ReviewResponseDto> findReview(User user) { return reviewsByUserId.stream().map(this::toDto).toList(); } + @Transactional(readOnly = true) + public List<ReviewResponseDto> findItemReviews(Long itemId, int page, int size) { + Pageable pageable = PageRequest.of(page - 1, size); + Slice<Review> reviews = reviewRepository.findReviewsByItemId(itemId, pageable); + return reviews.stream().map(this::toDto).toList(); + } + @Transactional public void updateReview(Long id, UserDetailsImpl userDetails, UpdateReviewRequestDto updateReviewRequestDto) { - Review review = reviewRepository.findMyReview(id, userDetails.getUser().getId()); + Review review = getMyReview(id, userDetails.getUser()); // ์ด๋ฏธ์ง€ ๊ด€๋ จ ์ฒ˜๋ฆฌ - handlePoint(review, updateReviewRequestDto.getImage()); - - // ๋‚˜๋จธ์ง€ ํ•„๋“œ ์—…๋ฐ์ดํŠธ - review.update(updateReviewRequestDto); + String image = null; + if (hasImage(updateReviewRequestDto.getImage())) { + image = imageService.UploadImage(review.getReviewImage(), updateReviewRequestDto.getImage()); + } + pointService.handlePoint(userDetails.getUser(), review.getReviewImage(), updateReviewRequestDto.getImage()); + // ํ•„๋“œ ์—…๋ฐ์ดํŠธ + review.update(updateReviewRequestDto, image); } @Transactional public void deleteReview(Long id, User user) { - Review review = reviewRepository.findMyReview(id, user.getId()); - if (review.getReviewImage() != null) { - review.getUser().minusPoint(TEXT_IMAGE_POINT); - } else { - review.getUser().minusPoint(TEXT_ONLY_POINT); - } + Review review = getMyReview(id, user); + pointService.deletePoint(user, review.getReviewImage()); reviewRepository.delete(review); } - private void handlePoint(Review review, MultipartFile newImage) { - try { - if (newImage != null) { - if (review.getReviewImage() == null) { - review.getUser().addPoint(DIFFERENCE_POINT); - } - // ์ƒˆ ์ด๋ฏธ์ง€ ์—…๋กœ๋“œ - reUploadImage(review, newImage); - - } else { - if (review.getReviewImage() != null) { - s3Uploader.deleteImage(review.getReviewImage()); - review.deleteImage(); - review.getUser().minusPoint(DIFFERENCE_POINT); - } - } - } catch (IOException e) { - throw new CommonException(ErrorCode.FAILED_UPLOAD_IMAGE); - } + private Review getMyReview(Long id, User user) { + return reviewRepository.findMyReview(id, user.getId()); + } + + private static boolean hasImage(MultipartFile multipartFile) { + return multipartFile != null && !multipartFile.isEmpty(); } /** @@ -138,48 +125,4 @@ private ReviewResponseDto toDto(Review review) { .build(); } - /** - * ์ด๋ฏธ์ง€ ์—…๋กœ๋“œ ๋ฉ”์†Œ๋“œ - * - * @param file - * @return - */ - private String uploadImage(MultipartFile file) { - - try { - return s3Uploader.upload(file); - - } catch (IOException e) { - throw new CommonException(ErrorCode.FAILED_UPLOAD_IMAGE); - } - } - - /** - * ์ด๋ฏธ์ง€ ์žฌ์—…๋กœ๋“œ ๋ฉ”์†Œ๋“œ (๊ธฐ์กด ์ด๋ฏธ์ง€ ์‚ญ์ œ ํ›„ ์—…๋กœ๋“œ) - * - * @param review - * @param file - */ - private void reUploadImage(Review review, MultipartFile file) { - - try { - if (review.getReviewImage() != null) { - s3Uploader.deleteImage(review.getReviewImage()); - } - - String imageUrl = uploadImage(file); - review.update(imageUrl); - - } catch (IOException e) { - throw new CommonException(ErrorCode.FAILED_UPLOAD_IMAGE); - } - - } - - @Transactional(readOnly = true) - public List<ReviewResponseDto> findItemReviews(Long itemId, int page, int size) { - Pageable pageable = PageRequest.of(page - 1, size); - List<Review> reviews = reviewRepository.findReviewsByItemId(itemId, pageable).stream().toList(); - return reviews.stream().map(this::toDto).toList(); - } }
Java
_:hammer_and_wrench: Refactor suggestion_ **๋ฆฌ๋ทฐ ์‚ญ์ œ ์‹œ ์ด๋ฏธ์ง€ ์ œ๊ฑฐ ๊ณ ๋ ค** ํฌ์ธํŠธ ์ฐจ๊ฐ ํ›„ ๋ฆฌ๋ทฐ๋ฅผ ์‚ญ์ œํ•˜์ง€๋งŒ, ์‹ค์ œ ์ด๋ฏธ์ง€ ํŒŒ์ผ ์‚ญ์ œ ๋กœ์ง์€ ๋ˆ„๋ฝ๋œ ๊ฒƒ์œผ๋กœ ๋ณด์ž…๋‹ˆ๋‹ค. ๋ถˆํ•„์š”ํ•ด์ง„ ์ด๋ฏธ์ง€๋ฅผ ์ •๋ฆฌํ•˜๋ ค๋ฉด `imageService.deleteImage(...)` ํ˜ธ์ถœ๋„ ๊ณ ๋ คํ•ด์ฃผ์„ธ์š”. ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์ˆ˜์ • ์˜ˆ์‹œ๋ฅผ ์ฐธ๊ณ ํ•ด ๋ณด์‹ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค: ```diff 98 Review review = getMyReview(id, user); 99 pointService.deletePoint(user, review.getReviewImage()); + imageService.deleteImage(review.getReviewImage()); reviewRepository.delete(review); ``` <!-- suggestion_start --> <details> <summary>๐Ÿ“ Committable suggestion</summary> > โ€ผ๏ธ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. `````suggestion Review review = getMyReview(id, user); pointService.deletePoint(user, review.getReviewImage()); imageService.deleteImage(review.getReviewImage()); reviewRepository.delete(review); ````` </details> <!-- suggestion_end --> <!-- This is an auto-generated comment by CodeRabbit -->
@@ -47,18 +47,11 @@ public class Review extends BaseTimeEntity { private User user; - public void update(UpdateReviewRequestDto updateReviewRequestDto) { + public void update(UpdateReviewRequestDto updateReviewRequestDto, String image) { this.starRate = updateReviewRequestDto.getStarRate(); this.title = updateReviewRequestDto.getTitle(); this.content = updateReviewRequestDto.getContent(); + this.reviewImage = image; } - - public void update(String reviewImage) { - this.reviewImage = reviewImage; - } - - public void deleteImage() { - this.reviewImage = null; - } }
Java
_:hammer_and_wrench: Refactor suggestion_ **์ด๋ฏธ์ง€ ์—…๋ฐ์ดํŠธ ๋กœ์ง ํ†ตํ•ฉ์— ๋Œ€ํ•œ ํ”ผ๋“œ๋ฐฑ** ์ด๋ฏธ์ง€ ์—…๋ฐ์ดํŠธ ๋กœ์ง์„ ํ•˜๋‚˜์˜ ๋ฉ”์„œ๋“œ๋กœ ํ†ตํ•ฉํ•œ ๊ฒƒ์€ ์ข‹์€ ์ ‘๊ทผ์ž…๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ ๋ช‡ ๊ฐ€์ง€ ๊ฐœ์„ ์‚ฌํ•ญ์„ ์ œ์•ˆ๋“œ๋ฆฝ๋‹ˆ๋‹ค: 1. ์ž…๋ ฅ๊ฐ’ ๊ฒ€์ฆ์ด ๋ˆ„๋ฝ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. 2. ์ด๋ฏธ์ง€ ์ฒ˜๋ฆฌ ๋กœ์ง์ด ๋„๋ฉ”์ธ ๋ชจ๋ธ์— ์ง์ ‘ ๋…ธ์ถœ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๊ฐœ์„ ํ•ด๋ณด์‹œ๋Š” ๊ฒƒ์€ ์–ด๋–จ๊นŒ์š”: ```diff public void update(UpdateReviewRequestDto updateReviewRequestDto, String image) { + validateUpdateRequest(updateReviewRequestDto); this.starRate = updateReviewRequestDto.getStarRate(); this.title = updateReviewRequestDto.getTitle(); this.content = updateReviewRequestDto.getContent(); this.reviewImage = image; } +private void validateUpdateRequest(UpdateReviewRequestDto dto) { + if (dto.getStarRate() == null || dto.getStarRate() < 1 || dto.getStarRate() > 5) { + throw new IllegalArgumentException("๋ณ„์ ์€ 1-5 ์‚ฌ์ด์˜ ๊ฐ’์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค."); + } + if (dto.getTitle() == null || dto.getTitle().trim().isEmpty()) { + throw new IllegalArgumentException("์ œ๋ชฉ์€ ํ•„์ˆ˜ ์ž…๋ ฅ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } + if (dto.getContent() == null || dto.getContent().trim().isEmpty()) { + throw new IllegalArgumentException("๋‚ด์šฉ์€ ํ•„์ˆ˜ ์ž…๋ ฅ๊ฐ’์ž…๋‹ˆ๋‹ค."); + } +} ``` <!-- suggestion_start --> <details> <summary>๐Ÿ“ Committable suggestion</summary> > โ€ผ๏ธ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. `````suggestion public void update(UpdateReviewRequestDto updateReviewRequestDto, String image) { validateUpdateRequest(updateReviewRequestDto); this.starRate = updateReviewRequestDto.getStarRate(); this.title = updateReviewRequestDto.getTitle(); this.content = updateReviewRequestDto.getContent(); this.reviewImage = image; } private void validateUpdateRequest(UpdateReviewRequestDto dto) { if (dto.getStarRate() == null || dto.getStarRate() < 1 || dto.getStarRate() > 5) { throw new IllegalArgumentException("๋ณ„์ ์€ 1-5 ์‚ฌ์ด์˜ ๊ฐ’์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค."); } if (dto.getTitle() == null || dto.getTitle().trim().isEmpty()) { throw new IllegalArgumentException("์ œ๋ชฉ์€ ํ•„์ˆ˜ ์ž…๋ ฅ๊ฐ’์ž…๋‹ˆ๋‹ค."); } if (dto.getContent() == null || dto.getContent().trim().isEmpty()) { throw new IllegalArgumentException("๋‚ด์šฉ์€ ํ•„์ˆ˜ ์ž…๋ ฅ๊ฐ’์ž…๋‹ˆ๋‹ค."); } } ````` </details> <!-- suggestion_end --> <!-- This is an auto-generated comment by CodeRabbit -->
@@ -0,0 +1,52 @@ +package com.doubleowner.revibe.domain.point; + +import com.doubleowner.revibe.domain.user.entity.User; +import com.doubleowner.revibe.domain.user.repository.UserRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; + +@Service +@RequiredArgsConstructor +public class PointService { + private final UserRepository userRepository; + + @Transactional + public void addReviewPoint(User user, String image) { + int point = PointPolicy.TEXT_ONLY_POINT.getPoint(); + if (image != null) { + point = PointPolicy.TEXT_IMAGE_POINT.getPoint(); + } + User findUser = userRepository.findByEmailOrElseThrow(user.getEmail()); + findUser.addPoint(point); + + + } + + @Transactional + public void handlePoint(User user, String preImage, MultipartFile afterImage) { + + int pointChange = 0; + if (preImage != null && afterImage == null) { + pointChange = PointPolicy.TEXT_ONLY_POINT.getPoint() - PointPolicy.TEXT_IMAGE_POINT.getPoint(); + } else if (preImage == null && afterImage != null) { + pointChange = PointPolicy.TEXT_IMAGE_POINT.getPoint() - PointPolicy.TEXT_ONLY_POINT.getPoint(); + } + if (pointChange != 0) { + User findUser = userRepository.findByEmailOrElseThrow(user.getEmail()); + findUser.addPoint(pointChange); + } + } + + @Transactional + public void deletePoint(User user, String image) { + int point = (image != null) + ? PointPolicy.TEXT_IMAGE_POINT.getPoint() + : PointPolicy.TEXT_ONLY_POINT.getPoint(); + + User findUser = userRepository.findByEmailOrElseThrow(user.getEmail()); + findUser.addPoint(-point); // ํฌ์ธํŠธ ์ฐจ๊ฐ + } +} +
Java
_:hammer_and_wrench: Refactor suggestion_ **ํฌ์ธํŠธ ์ ๋ฆฝ ๋กœ์ง ๊ฐœ์„  ํ•„์š”** ํฌ์ธํŠธ ์ ๋ฆฝ ๋กœ์ง์— ๋Œ€ํ•œ ๊ฐœ์„ ์‚ฌํ•ญ์„ ์ œ์•ˆ๋“œ๋ฆฝ๋‹ˆ๋‹ค: 1. null ์ฒดํฌ๊ฐ€ ๋ถˆ์ถฉ๋ถ„ํ•ฉ๋‹ˆ๋‹ค. 2. ์‚ฌ์šฉ์ž ์กฐํšŒ์™€ ํฌ์ธํŠธ ์ ๋ฆฝ์ด ๋ถ„๋ฆฌ๋˜์–ด ์žˆ์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๊ฐœ์„ ํ•ด๋ณด์‹œ๋Š” ๊ฒƒ์€ ์–ด๋–จ๊นŒ์š”: ```diff @Transactional public void addReviewPoint(User user, String image) { + if (user == null) { + throw new IllegalArgumentException("์‚ฌ์šฉ์ž ์ •๋ณด๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค."); + } int point = PointPolicy.TEXT_ONLY_POINT.getPoint(); if (image != null) { point = PointPolicy.TEXT_IMAGE_POINT.getPoint(); } User findUser = userRepository.findByEmailOrElseThrow(user.getEmail()); findUser.addPoint(point); - } ``` <!-- suggestion_start --> <details> <summary>๐Ÿ“ Committable suggestion</summary> > โ€ผ๏ธ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. `````suggestion @Transactional public void addReviewPoint(User user, String image) { if (user == null) { throw new IllegalArgumentException("์‚ฌ์šฉ์ž ์ •๋ณด๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค."); } int point = PointPolicy.TEXT_ONLY_POINT.getPoint(); if (image != null) { point = PointPolicy.TEXT_IMAGE_POINT.getPoint(); } User findUser = userRepository.findByEmailOrElseThrow(user.getEmail()); findUser.addPoint(point); } ````` </details> <!-- suggestion_end --> <!-- This is an auto-generated comment by CodeRabbit -->
@@ -0,0 +1,52 @@ +package com.doubleowner.revibe.domain.point; + +import com.doubleowner.revibe.domain.user.entity.User; +import com.doubleowner.revibe.domain.user.repository.UserRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; + +@Service +@RequiredArgsConstructor +public class PointService { + private final UserRepository userRepository; + + @Transactional + public void addReviewPoint(User user, String image) { + int point = PointPolicy.TEXT_ONLY_POINT.getPoint(); + if (image != null) { + point = PointPolicy.TEXT_IMAGE_POINT.getPoint(); + } + User findUser = userRepository.findByEmailOrElseThrow(user.getEmail()); + findUser.addPoint(point); + + + } + + @Transactional + public void handlePoint(User user, String preImage, MultipartFile afterImage) { + + int pointChange = 0; + if (preImage != null && afterImage == null) { + pointChange = PointPolicy.TEXT_ONLY_POINT.getPoint() - PointPolicy.TEXT_IMAGE_POINT.getPoint(); + } else if (preImage == null && afterImage != null) { + pointChange = PointPolicy.TEXT_IMAGE_POINT.getPoint() - PointPolicy.TEXT_ONLY_POINT.getPoint(); + } + if (pointChange != 0) { + User findUser = userRepository.findByEmailOrElseThrow(user.getEmail()); + findUser.addPoint(pointChange); + } + } + + @Transactional + public void deletePoint(User user, String image) { + int point = (image != null) + ? PointPolicy.TEXT_IMAGE_POINT.getPoint() + : PointPolicy.TEXT_ONLY_POINT.getPoint(); + + User findUser = userRepository.findByEmailOrElseThrow(user.getEmail()); + findUser.addPoint(-point); // ํฌ์ธํŠธ ์ฐจ๊ฐ + } +} +
Java
_:hammer_and_wrench: Refactor suggestion_ **ํฌ์ธํŠธ ์ฐจ๊ฐ ๋กœ์ง ๊ฐœ์„  ํ•„์š”** ํฌ์ธํŠธ ์ฐจ๊ฐ ๋กœ์ง์— ๋Œ€ํ•œ ๊ฐœ์„ ์‚ฌํ•ญ์ž…๋‹ˆ๋‹ค: 1. ์‚ญ์ œ ์‹œ ํฌ์ธํŠธ๊ฐ€ ์Œ์ˆ˜๊ฐ€ ๋˜๋Š” ๊ฒฝ์šฐ์— ๋Œ€ํ•œ ์ฒ˜๋ฆฌ๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. 2. ์ฝ”๋“œ ๊ฐ€๋…์„ฑ ๊ฐœ์„ ์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๊ฐœ์„ ํ•ด๋ณด์‹œ๋Š” ๊ฒƒ์€ ์–ด๋–จ๊นŒ์š”: ```diff @Transactional public void deletePoint(User user, String image) { + if (user == null) { + throw new IllegalArgumentException("์‚ฌ์šฉ์ž ์ •๋ณด๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค."); + } - int point = (image != null) - ? PointPolicy.TEXT_IMAGE_POINT.getPoint() - : PointPolicy.TEXT_ONLY_POINT.getPoint(); + int pointToDeduct = calculatePointToDeduct(image); User findUser = userRepository.findByEmailOrElseThrow(user.getEmail()); - findUser.addPoint(-point); // ํฌ์ธํŠธ ์ฐจ๊ฐ + if (findUser.getPoint() < pointToDeduct) { + throw new IllegalStateException("์ฐจ๊ฐํ•  ํฌ์ธํŠธ๊ฐ€ ๋ณด์œ  ํฌ์ธํŠธ๋ณด๋‹ค ๋งŽ์Šต๋‹ˆ๋‹ค."); + } + findUser.addPoint(-pointToDeduct); } +private int calculatePointToDeduct(String image) { + return image != null + ? PointPolicy.TEXT_IMAGE_POINT.getPoint() + : PointPolicy.TEXT_ONLY_POINT.getPoint(); +} ``` <!-- suggestion_start --> <details> <summary>๐Ÿ“ Committable suggestion</summary> > โ€ผ๏ธ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. `````suggestion @Transactional public void deletePoint(User user, String image) { if (user == null) { throw new IllegalArgumentException("์‚ฌ์šฉ์ž ์ •๋ณด๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค."); } int pointToDeduct = calculatePointToDeduct(image); User findUser = userRepository.findByEmailOrElseThrow(user.getEmail()); if (findUser.getPoint() < pointToDeduct) { throw new IllegalStateException("์ฐจ๊ฐํ•  ํฌ์ธํŠธ๊ฐ€ ๋ณด์œ  ํฌ์ธํŠธ๋ณด๋‹ค ๋งŽ์Šต๋‹ˆ๋‹ค."); } findUser.addPoint(-pointToDeduct); } private int calculatePointToDeduct(String image) { return image != null ? PointPolicy.TEXT_IMAGE_POINT.getPoint() : PointPolicy.TEXT_ONLY_POINT.getPoint(); } ````` </details> <!-- suggestion_end --> <!-- This is an auto-generated comment by CodeRabbit -->
@@ -16,7 +16,8 @@ import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class ProfileFragment : Fragment() { - private lateinit var binding: FragmentProfileBinding //๋ทฐ ๋ฐ”์ธ๋”ฉ + private var _binding: FragmentProfileBinding? = null //๋ทฐ ๋ฐ”์ธ๋”ฉ + private val binding get() = _binding!! private var selectedBadges = ArrayList<Badge>() //๋Œ€ํ‘œ ๋ฑƒ์ง€ ๋ฆฌ์ŠคํŠธ private val userViewModel: UserViewModel by viewModels() private val profileCommon = ProfileCommon() //๊ณตํ†ต ๋กœ์ง ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ @@ -25,18 +26,11 @@ class ProfileFragment : Fragment() { inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { - binding = FragmentProfileBinding.inflate(inflater, container, false) + _binding = FragmentProfileBinding.inflate(inflater, container, false) //ViewPager2 Adapter ์—ฐ๊ฒฐ profileCommon.setupViewPager(binding, requireActivity(), true) - //ํŒ”๋กœ์šฐ ํด๋ฆญ ์ฒ˜๋ฆฌ - profileCommon.onFollowClicked(requireActivity(), binding.llProfileFollower, "follower") - profileCommon.onFollowClicked(requireActivity(), binding.llProfileFollowing, "following") - - //ํด๋ฆญ ์ด๋ฒคํŠธ ์ฒ˜๋ฆฌ ์„ค์ • - initClickListener() - // LiveData ๊ด€์ฐฐ (๋ฐ์ดํ„ฐ๊ฐ€ ๋ณ€๊ฒฝ๋  ๋•Œ ์ž๋™ ์—…๋ฐ์ดํŠธ๋˜๋„๋ก ์„ค์ •) userViewModel.profile.observe(viewLifecycleOwner) { profile -> profile?.let { @@ -51,10 +45,20 @@ class ProfileFragment : Fragment() { userViewModel.errorMessage.observe(viewLifecycleOwner) { errorMsg -> errorMsg?.let { - Toast.makeText(requireContext(), it, Toast.LENGTH_LONG).show() + val errorToUser = when { + it.contains("IllegalStateException") -> "๋ฐ์ดํ„ฐ๋ฅผ ๋ถˆ๋Ÿฌ์˜ค๋Š” ์ค‘ ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์‹œ๋„ํ•ด ์ฃผ์„ธ์š”." + it.contains("JsonSyntaxException") -> "์„œ๋ฒ„ ์‘๋‹ต์ด ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ์—…๋ฐ์ดํŠธ๋ฅผ ํ™•์ธํ•ด ์ฃผ์„ธ์š”." + it.contains("SocketTimeoutException") -> "์„œ๋ฒ„ ์‘๋‹ต์ด ์ง€์—ฐ๋˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ์ž ์‹œ ํ›„ ๋‹ค์‹œ ์‹œ๋„ํ•ด ์ฃผ์„ธ์š”." + it.contains("IOException") -> "๋„คํŠธ์›Œํฌ ์—ฐ๊ฒฐ์„ ํ™•์ธํ•ด ์ฃผ์„ธ์š”." + else -> "์•Œ ์ˆ˜ ์—†๋Š” ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค. ์ž ์‹œ ํ›„ ๋‹ค์‹œ ์‹œ๋„ํ•ด ์ฃผ์„ธ์š”." + } + + Toast.makeText(requireContext(), errorToUser, Toast.LENGTH_LONG).show() + Log.e("ProfileFragmentVM", "์˜ค๋ฅ˜ ๋ฐœ์ƒ: $errorMsg") } } + // ์œ ์ € ๋ฐ์ดํ„ฐ ๋กœ๋“œ userViewModel.loadProfile() @@ -64,28 +68,39 @@ class ProfileFragment : Fragment() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) + //ํด๋ฆญ ์ด๋ฒคํŠธ ์ฒ˜๋ฆฌ ์„ค์ • + initClickListener() + //๋ ˆ๋ฒจ ๋‹ฌ์„ฑ๋ฅ  ๊ฒŒ์ด์ง€ ๋ฐ” ๊ตฌํ˜„ profileCommon.setupCircularProgressBar(binding, 76, 100) //๋ฑƒ์ง€ ๋”๋ฏธ ๋ฐ์ดํ„ฐ - ํ…Œ์ŠคํŠธ ์‹œ ์ฃผ์„ ํ•ด์ œ or ์„ค์ • selectedBadges.clear() selectedBadges.apply { - add(Badge("ํ”„๋กœ ์ฑŒ๋ฆฐ์ €", R.drawable.img_badge_challenge_01)) - add(Badge("์ˆ˜์ค€๊ธ‰ ์Šคํ„ฐ๋””์–ธ", R.drawable.img_badge_challenge_01)) - add(Badge("์šด๋™ ์Šคํƒ€ํ„ฐ", R.drawable.img_badge_challenge_01)) + add(Badge("ํ”„๋กœ ์ฑŒ๋ฆฐ์ €", R.drawable.badge_type_fromtoday_challenger)) + add(Badge("์ˆ˜์ค€๊ธ‰ ์Šคํ„ฐ๋””์–ธ", R.drawable.badge_type_fromtoday_challenger)) + add(Badge("์šด๋™ ์Šคํƒ€ํ„ฐ", R.drawable.badge_type_fromtoday_challenger)) } //์„ค์ •ํ•œ ๋Œ€ํ‘œ ๋ฑƒ์ง€ ๊ฐœ์ˆ˜์— ๋”ฐ๋ผ visibility ์กฐ์ • profileCommon.setupBadges(binding, selectedBadges) + + + } + + override fun onDestroyView() { + super.onDestroyView() + _binding = null + } + + private fun initClickListener() { // ์„ค์ • ๋ฒ„ํŠผ ํด๋ฆญ ์ฒ˜๋ฆฌ binding.ivProfileMenu.setOnClickListener { - // Fragment ์ „ํ™˜ - this.parentFragmentManager.beginTransaction() - .replace(R.id.main_frame, SettingFragment()) - .addToBackStack(null) - .commit() + val intent = Intent(requireContext(), ProfileMoreActivity::class.java) + intent.putExtra("type", "setting") + startActivity(intent) } // ํ”„๋กœํ•„ ์ˆ˜์ • ๋ชจ๋“œ @@ -94,22 +109,22 @@ class ProfileFragment : Fragment() { startActivity(intent) } + // ๋ ˆ๋ฒจ ํด๋ฆญ ์‹œ ๋ ˆ๋ฒจ ๋กœ๋“œ๋งต์œผ๋กœ ์ „ํ™˜ + binding.llProfileRank.setOnClickListener { + val intent = Intent(requireContext(), LevelActivity::class.java) + startActivity(intent) + } + + //ํŒ”๋กœ์šฐ ํด๋ฆญ ์ฒ˜๋ฆฌ + profileCommon.onFollowClicked(requireActivity(), binding.llProfileFollower, "follower") + profileCommon.onFollowClicked(requireActivity(), binding.llProfileFollowing, "following") + // ๋Œ€ํ‘œ ๋ฑƒ์ง€ ํด๋ฆญ ์‹œ ๋ฑƒ์ง€ ์ˆ˜์ • ํ™”๋ฉด์œผ๋กœ ์ „ํ™˜ binding.llProfileBadge.setOnClickListener { val intent = Intent(requireContext(), EditProfileActivity::class.java) intent.putExtra("clicked", "badge") startActivity(intent) } - - } - - private fun initClickListener() { - binding.llProfileRank.setOnClickListener { - parentFragmentManager.beginTransaction() - .replace(R.id.main_frame, ProfileLevelFragment()) - .addToBackStack(null) // ๋’ค๋กœ ๊ฐ€๊ธฐ ์ง€์› - .commit() - } } } \ No newline at end of file
Kotlin
์—๋Ÿฌ ๋ฉ”์‹œ์ง€ ์ฒ˜๋ฆฌ ๋ถ€๋ถ„์ด ํ›จ์”ฌ ์‚ฌ์šฉ์ž ์นœํ™”์ ์œผ๋กœ ๊ฐœ์„ ๋˜์—ˆ๋„ค์š”! ์—๋Ÿฌ ๋ฉ”์‹œ์ง€๊ฐ€ ๊ทธ๋Œ€๋กœ ๋ณด์—ฌ์กŒ๋˜ ์ „๊ณผ ๋‹ฌ๋ฆฌ, ์ด์ œ๋Š” ๊ฐ ์ƒํ™ฉ๋ณ„๋กœ ์‚ฌ์šฉ์ž๊ฐ€ ์ดํ•ดํ•˜๊ธฐ ์‰ฌ์šด ์•ˆ๋‚ด ๋ฉ”์‹œ์ง€๋กœ ๋ณ€ํ™˜๋˜์–ด ๋‚˜ํƒ€๋‚˜๋‹ˆ๊นŒ ์‚ฌ์šฉ์„ฑ์ด ํ›จ์”ฌ ์ข‹์•„์ง„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค๐Ÿ‘
@@ -1,19 +1,23 @@ package com.example.hrr_android import android.os.Bundle +import android.os.Handler +import android.os.Looper import android.util.Log +import android.widget.Toast +import androidx.activity.OnBackPressedCallback import androidx.appcompat.app.AppCompatActivity import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.setupWithNavController import com.example.hrr_android.databinding.ActivityMainBinding import dagger.hilt.android.AndroidEntryPoint -import com.example.hrr_android.message.ui.MessageFragment import com.google.android.material.bottomnavigation.BottomNavigationView @AndroidEntryPoint class MainActivity : AppCompatActivity() { - //๋ทฐ ๋ฐ”์ธ๋”ฉ - private lateinit var binding: ActivityMainBinding + private lateinit var binding: ActivityMainBinding // ๋ทฐ ๋ฐ”์ธ๋”ฉ + private var backPressedOnce = false // ๋’ค๋กœ๊ฐ€๊ธฐ ๋ฒ„ํŠผ ์ƒํƒœ ์ €์žฅ ๋ณ€์ˆ˜ + private val handler = Handler(Looper.getMainLooper()) // ์‹œ๊ฐ„ ์ดˆ๊ณผ ์ฒ˜๋ฆฌ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -24,6 +28,21 @@ class MainActivity : AppCompatActivity() { //๋ฐ”ํ…€ ๋„ค๋น„๊ฒŒ์ด์…˜ ์„ธํŒ… initBottomNavigation() + // ์‹œ์Šคํ…œ ๋’ค๋กœ๊ฐ€๊ธฐ ๋ฒ„ํŠผ์„ ๊ฐ์ง€ํ•ด์„œ ๋‘ ๋ฒˆ ๋ˆŒ๋ €์„ ๋•Œ ์ข…๋ฃŒ ์‹คํ–‰ + onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) { + override fun handleOnBackPressed() { + if (backPressedOnce) { + finish() // ์•ฑ ์ข…๋ฃŒ + } else { + backPressedOnce = true + Toast.makeText(this@MainActivity, "\"๋’ค๋กœ\" ๋ฒ„ํŠผ ํ•œ ๋ฒˆ ๋” ๋ˆ„๋ฅด์‹œ๋ฉด ์ข…๋ฃŒ๋ฉ๋‹ˆ๋‹ค.", Toast.LENGTH_SHORT).show() + + // 2์ดˆ ํ›„ ๋‹ค์‹œ false๋กœ ๋ณ€๊ฒฝํ•˜์—ฌ ์žฌ์ž…๋ ฅ ์š”๊ตฌ + handler.postDelayed({ backPressedOnce = false }, 2000) + } + } + }) + } private fun initBottomNavigation(){ @@ -41,8 +60,4 @@ class MainActivity : AppCompatActivity() { } - // ํ”„๋ž˜๊ทธ๋จผํŠธ์—์„œ ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋„๋ก ์ถ”๊ฐ€ - fun getBinding(): ActivityMainBinding { - return binding - } } \ No newline at end of file
Kotlin
๋’ค๋กœ๊ฐ€๊ธฐ๋ฅผ ๋‘ ๋ฒˆ ๋ˆŒ๋ €์„ ๋•Œ ์ข…๋ฃŒ๋˜๊ฒŒ๋” ์ถ”๊ฐ€ํ•˜์‹  ๊ฑฐ ์ข‹์€ UX ๊ฐœ์„ ์ธ ๊ฒƒ ๊ฐ™์•„์š”! handler๋กœ ํƒ€์ž„์•„์›ƒ ์ฒ˜๋ฆฌ๊นŒ์ง€ ๊ตฌํ˜„ํ•˜์‹  ๊ฑฐ ๊ตฟ์ž…๋‹ˆ๋‹ค๐Ÿ‘
@@ -10,22 +10,23 @@ import androidx.recyclerview.widget.LinearLayoutManager import com.example.hrr_android.databinding.FragmentProfileChallengeBinding class ProfileChallengeFragment : Fragment() { - private lateinit var binding: FragmentProfileChallengeBinding //๋ทฐ ๋ฐ”์ธ๋”ฉ + private var _binding: FragmentProfileChallengeBinding? = null //๋ทฐ ๋ฐ”์ธ๋”ฉ + private val binding get() = _binding!! private var participatingChallengeList = ArrayList<Challenge>() //์ฐธ๊ฐ€์ค‘์ธ ์ฑŒ๋ฆฐ์ง€ ๋ฆฌ์ŠคํŠธ private var completedChallengeList = ArrayList<Challenge>() //์ตœ๊ทผ ์™„์ฃผํ•œ ์ฑŒ๋ฆฐ์ง€ ๋ฆฌ์ŠคํŠธ override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { - binding = FragmentProfileChallengeBinding.inflate(inflater, container, false) + _binding = FragmentProfileChallengeBinding.inflate(inflater, container, false) //์ฐธ๊ฐ€์ค‘์ธ ์ฑŒ๋ฆฐ์ง€ ๋”๋ฏธ ๋ฐ์ดํ„ฐ - ํ…Œ์ŠคํŠธ ์‹œ ์ฃผ์„ ํ•ด์ œ or ์„ค์ • - participatingChallengeList.apply { - add(Challenge("ํ† ์ต 800์ ", R.drawable.img_english_book, isCertified = false)) - add(Challenge("ํ† ์ต 900์  ์ฐ๊ธฐ. ์ซ„?", R.drawable.img_english_book, isCertified = true)) - add(Challenge("์—ด ์ž ์ œํ•œ ํ…Œ์ŠคํŠธ", R.drawable.img_english_book, isCertified = true)) - } +// participatingChallengeList.apply { +// add(Challenge("ํ† ์ต 800์ ", R.drawable.img_english_book, isCertified = false)) +// add(Challenge("ํ† ์ต 900์  ์ฐ๊ธฐ. ์ซ„?", R.drawable.img_english_book, isCertified = true)) +// add(Challenge("์—ด ์ž ์ œํ•œ ํ…Œ์ŠคํŠธ", R.drawable.img_english_book, isCertified = true)) +// } //์ตœ๊ทผ ์™„์ฃผํ•œ ์ฑŒ๋ฆฐ์ง€ ๋”๋ฏธ ๋ฐ์ดํ„ฐ - ํ…Œ์ŠคํŠธ ์‹œ ์ฃผ์„ ํ•ด์ œ or ์„ค์ • completedChallengeList.apply { @@ -58,7 +59,7 @@ class ProfileChallengeFragment : Fragment() { binding.rvProfileCompletedChallengeContent.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false) //๋”๋ณด๊ธฐ ๋ฒ„ํŠผ ํด๋ฆญ ์ฒ˜๋ฆฌ - binding.llProfileCompletedChallengeMore.setOnClickListener { + binding.llProfileCompletedChallengeTitle.setOnClickListener { val intent = Intent(requireContext(), ProfileMoreActivity::class.java) intent.putExtra("type", "challenge") startActivity(intent) @@ -67,4 +68,9 @@ class ProfileChallengeFragment : Fragment() { return binding.root } + override fun onDestroyView() { + super.onDestroyView() + _binding = null + } + } \ No newline at end of file
Kotlin
`onDestroyView()` ๋ฉ”์„œ๋“œ๋ฅผ ์ถ”๊ฐ€ํ•ด ์ฃผ์…จ๋„ค์š”! ์ด์ „์— PR ๋ฆฌ๋ทฐ์—์„œ **BaseFragment**์— ๋Œ€ํ•ด ๋ง์”€๋“œ๋ ธ๋˜ ์  ์žˆ๋Š” ๊ฒƒ ๊ฐ™์€๋ฐ, ์ด๋ฒˆ์— ์ปค๋ฐ‹ ํ•˜์‹  ๊ฑฐ ๋ณด๊ณ  ๋‚˜๋‹ˆ๊นŒ.. ์ €ํฌ๊ฐ€ ๋ทฐ ๋ฐ”์ธ๋”ฉ ์ดˆ๊ธฐํ™”๋ž‘ ํ•ด์ œ ๋กœ์ง์ด ๊ฑฐ์˜ ๋ชจ๋“  ํ”„๋ž˜๊ทธ๋จผํŠธ์—์„œ ๋ฐ˜๋ณต๋˜๊ณ  ์žˆ์ž–์•„์š”?! ์ด๋Ÿฐ ๊ณตํ†ต ๋กœ์ง๋“ค์„ BaseFragment๋กœ ์ถ”์ƒํ™”ํ•ด์„œ ์ผ์œผ๋ฉด ์ฝ”๋“œ์— ๋ˆ„๋ฝ๋˜๋Š” ์ผ๋„ ์—†๊ณ  ๋” ๊ฐ„ํŽธํ–ˆ์—ˆ์„ ๊ฑฐ ๊ฐ™๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“œ๋„ค์š”..๐Ÿค” ์ด๋ฒˆ์— ํ”„๋กœ์ ํŠธ ์ง„ํ–‰ํ•˜๋ฉด์„œ ๊นจ๋‹ฌ์•˜์œผ๋‹ˆ ๋‹ค์Œ๋ฒˆ๋ถ€ํ„ฐ๋Š” ์ด์  ์ฐธ๊ณ ํ•ด์„œ ์ž‘์—…ํ•ด์•ผ๊ฒ ์Šต๋‹ˆ๋‹ค๐Ÿค“
@@ -0,0 +1,66 @@ +package blackjack.controller; + +import blackjack.domain.card.Deck; +import blackjack.domain.participant.Dealer; +import blackjack.domain.participant.Player; +import blackjack.domain.participant.PlayersFactory; +import blackjack.domain.result.GameResult; +import blackjack.dto.DrawCardRequestDto; +import blackjack.dto.PlayersNameInputDto; +import blackjack.view.InputView; +import blackjack.view.OutputView; + +import java.util.List; + +public class BlackJackController { + private final InputView inputView = new InputView(); + private final OutputView outputView = new OutputView(); + + public void run() { + PlayersNameInputDto namesInput = inputView.getPlayersName(); + Dealer dealer = new Dealer(); + Deck deck = new Deck(); + List<Player> players = PlayersFactory.createPlayers(namesInput.getPlayersName()); + + drawTowCards(dealer, players, deck); + drawCardToPlayers(players, deck); + drawCardToDealer(dealer, deck); + outputView.printCardsResult(dealer, players); + outputView.printGameResult(GameResult.of(dealer, players)); + } + + private void drawTowCards(Dealer dealer, List<Player> players, Deck deck) { + for (Player player : players) { + player.receiveCard(deck.drawCard()); + player.receiveCard(deck.drawCard()); + } + dealer.receiveCard(deck.drawCard()); + dealer.receiveCard(deck.drawCard()); + outputView.printFirstCardsGiven(players, dealer); + outputView.printDealerCard(dealer); + outputView.printPlayersCard(players); + } + + private void drawCardToPlayers(List<Player> players, Deck deck) { + for (Player player : players) { + drawCardToPlayer(player, deck); + } + } + + private void drawCardToPlayer(Player player, Deck deck) { + DrawCardRequestDto drawCardRequest = inputView.getPlayersResponse(player); + while (player.drawable() && drawCardRequest.isYes()) { + player.receiveCard(deck.drawCard()); + + outputView.printCards(player); + drawCardRequest = inputView.getPlayersResponse(player); + } + } + + private void drawCardToDealer(Dealer dealer, Deck deck) { + while (dealer.drawable()) { + dealer.receiveCard(deck.drawCard()); + outputView.printDealerCardGiven(); + } + } +}
Java
Controller๋ฅผ Entry-point๋กœ์จ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ๋Š”๋ฐ, ํ˜„์žฌ์™€ ๊ฐ™์ด ํ•ด๋‹น ๊ฐ’๋“ค์„ ์ด๋ฅผ ๋ฉค๋ฒ„๋ณ€์ˆ˜๋กœ ๊ฐ€์ง€๊ฒŒ ๋˜๋ฉด ํ•ด๋‹น ๊ฒŒ์ž„์„ ์—ฌ๋Ÿฌ๋ช…์ด ๋™์‹œ์— ์š”์ฒญํ•˜๋Š” ๊ฒฝ์šฐ ๋ฐ์ดํ„ฐ ๋ถ€์ •ํ•ฉ์ด ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ์–ด์š”. ๋ฉค๋ฒ„๋ณ€์ˆ˜๋ฅผ ์ง€์—ญ๋ณ€์ˆ˜๋กœ ๊ฐ€์ ธ๊ฐ€๋Š” ๊ฒƒ์ด ์ข‹์•„ ๋ณด์—ฌ์š”๐Ÿ™‚
@@ -0,0 +1,66 @@ +package blackjack.controller; + +import blackjack.domain.card.Deck; +import blackjack.domain.participant.Dealer; +import blackjack.domain.participant.Player; +import blackjack.domain.participant.PlayersFactory; +import blackjack.domain.result.GameResult; +import blackjack.dto.DrawCardRequestDto; +import blackjack.dto.PlayersNameInputDto; +import blackjack.view.InputView; +import blackjack.view.OutputView; + +import java.util.List; + +public class BlackJackController { + private final InputView inputView = new InputView(); + private final OutputView outputView = new OutputView(); + + public void run() { + PlayersNameInputDto namesInput = inputView.getPlayersName(); + Dealer dealer = new Dealer(); + Deck deck = new Deck(); + List<Player> players = PlayersFactory.createPlayers(namesInput.getPlayersName()); + + drawTowCards(dealer, players, deck); + drawCardToPlayers(players, deck); + drawCardToDealer(dealer, deck); + outputView.printCardsResult(dealer, players); + outputView.printGameResult(GameResult.of(dealer, players)); + } + + private void drawTowCards(Dealer dealer, List<Player> players, Deck deck) { + for (Player player : players) { + player.receiveCard(deck.drawCard()); + player.receiveCard(deck.drawCard()); + } + dealer.receiveCard(deck.drawCard()); + dealer.receiveCard(deck.drawCard()); + outputView.printFirstCardsGiven(players, dealer); + outputView.printDealerCard(dealer); + outputView.printPlayersCard(players); + } + + private void drawCardToPlayers(List<Player> players, Deck deck) { + for (Player player : players) { + drawCardToPlayer(player, deck); + } + } + + private void drawCardToPlayer(Player player, Deck deck) { + DrawCardRequestDto drawCardRequest = inputView.getPlayersResponse(player); + while (player.drawable() && drawCardRequest.isYes()) { + player.receiveCard(deck.drawCard()); + + outputView.printCards(player); + drawCardRequest = inputView.getPlayersResponse(player); + } + } + + private void drawCardToDealer(Dealer dealer, Deck deck) { + while (dealer.drawable()) { + dealer.receiveCard(deck.drawCard()); + outputView.printDealerCardGiven(); + } + } +}
Java
๋ฉ”์†Œ๋“œ ๋ถ„๋ฆฌ๊ฐ€ ์ž˜ ๋˜์–ด ์žˆ์–ด์„œ, ๊ฐ€๋…์„ฑ์ด ์ข‹๋„ค์š”๐Ÿ™‚
@@ -0,0 +1,66 @@ +package blackjack.controller; + +import blackjack.domain.card.Deck; +import blackjack.domain.participant.Dealer; +import blackjack.domain.participant.Player; +import blackjack.domain.participant.PlayersFactory; +import blackjack.domain.result.GameResult; +import blackjack.dto.DrawCardRequestDto; +import blackjack.dto.PlayersNameInputDto; +import blackjack.view.InputView; +import blackjack.view.OutputView; + +import java.util.List; + +public class BlackJackController { + private final InputView inputView = new InputView(); + private final OutputView outputView = new OutputView(); + + public void run() { + PlayersNameInputDto namesInput = inputView.getPlayersName(); + Dealer dealer = new Dealer(); + Deck deck = new Deck(); + List<Player> players = PlayersFactory.createPlayers(namesInput.getPlayersName()); + + drawTowCards(dealer, players, deck); + drawCardToPlayers(players, deck); + drawCardToDealer(dealer, deck); + outputView.printCardsResult(dealer, players); + outputView.printGameResult(GameResult.of(dealer, players)); + } + + private void drawTowCards(Dealer dealer, List<Player> players, Deck deck) { + for (Player player : players) { + player.receiveCard(deck.drawCard()); + player.receiveCard(deck.drawCard()); + } + dealer.receiveCard(deck.drawCard()); + dealer.receiveCard(deck.drawCard()); + outputView.printFirstCardsGiven(players, dealer); + outputView.printDealerCard(dealer); + outputView.printPlayersCard(players); + } + + private void drawCardToPlayers(List<Player> players, Deck deck) { + for (Player player : players) { + drawCardToPlayer(player, deck); + } + } + + private void drawCardToPlayer(Player player, Deck deck) { + DrawCardRequestDto drawCardRequest = inputView.getPlayersResponse(player); + while (player.drawable() && drawCardRequest.isYes()) { + player.receiveCard(deck.drawCard()); + + outputView.printCards(player); + drawCardRequest = inputView.getPlayersResponse(player); + } + } + + private void drawCardToDealer(Dealer dealer, Deck deck) { + while (dealer.drawable()) { + dealer.receiveCard(deck.drawCard()); + outputView.printDealerCardGiven(); + } + } +}
Java
DTO๋„ ์ž์‹ ์ด ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ๋ฐ์ดํ„ฐ์— ๋Œ€ํ•ด์„œ, ์–ด๋–ค ํ–‰์œ„/ํŒ๋‹จ์„ ํ•  ์ˆ˜ ์žˆ๋‹ค๊ณ  ์ƒ๊ฐํ•ด์š”. ์ž…๋ ฅ๋ฐ›์€ ๊ฐ’์ด Y/N์ธ์ง€ ํŒ๋‹จํ•˜๋Š” ๋กœ์ง์€ DTO๋กœ ๊ฐ€๋„ ๋œ๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. ๋‹ค๋งŒ ํ•ด๋‹น ๋กœ์ง์ด ์—ฌ๋Ÿฌ ๊ณณ์—์„œ ์‚ฌ์šฉ๋˜๊ฑฐ๋‚˜, ์ด๋ฅผ ํ•˜๋‚˜์˜ ๋„๋ฉ”์ธ ํ–‰์œ„๋กœ ์ •์˜ํ•œ๋‹ค๋ฉด DTO -> Domain์œผ๋กœ ์ „ํ™˜ํ•œ ๋‹ค์Œ ๋„๋ฉ”์ธ์—์„œ ํŒ๋‹จํ•˜๋Š” ๊ฒƒ๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”. ํ˜„์žฌ๋Š” ํ•ด๋‹น ๋ถ€๋ถ„์— ๋Œ€ํ•œ ๋„๋ฉ”์ธ ๋กœ์ง์ด Controller์— ๋‚˜์™€ ์žˆ๊ธฐ์— ์›ํ•˜์‹œ๋Š” ํ˜•ํƒœ๋กœ ํฌ์žฅํ•ด์ฃผ์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค๐Ÿ™‚ ์ถ”๊ฐ€๋กœ ๋„ค์ด๋ฐ์€ ํŒ€๋ฐ”ํŒ€์ด๊ณ  ์‚ฌ๋ฐ”์‚ฌ์ง€๋งŒ, ๊ฐœ์ธ์ ์œผ๋กœ ํ”„๋กœ๊ทธ๋žจ์—๊ฒŒ ๋„˜์–ด์˜จ Input์„ ๋‹ด๋Š” DTO๋Š” Request/์šฐ๋ฆฌ ํ”„๋กœ๊ทธ๋žจ์—์„œ ๋ฐ˜ํ™˜ํ•ด์ฃผ๋Š”DTO๋Š” Response๋กœ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ์–ด์š”. response๋กœ ์ž‘์„ฑํ•ด์ฃผ์‹  ๋งฅ๋ฝ์€ ์•Œ๊ฒ ์œผ๋‚˜, Client-Server๊ฐ€ ํ•ญ์ƒ ์œ ๋™์ ์œผ๋กœ ๋‹ฌ๋ผ์งˆ ์ˆ˜ ์žˆ๋‹ค๋ฉด DTO๊ฐ€ ๋งŽ์•„์กŒ์„ ๋•Œ ํ—ท๊ฐˆ๋ฆด ์ˆ˜ ์žˆ๋‹ค๊ณ  ์ƒ๊ฐํ•ด์š”๐Ÿ™‚ (์ถ”๊ฐ€๋กœ DTO๋Š” > Dto๋กœ ์ ๊ณ  ์žˆ๊ธดํ•ฉ๋‹ˆ๋‹ค - ์ทจํ–ฅ)
@@ -0,0 +1,17 @@ +package blackjack.utils; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class StringUtil { + private static final String COMMA = ","; + private static final String RESPONSE_RESTRICT_MESSAGE = "y ํ˜น์€ n ๋งŒ ์ž…๋ ฅํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค."; + + public static List<String> splitByComma(String input) { + List<String> names = Arrays.asList(input.split(COMMA)); + return names.stream() + .map(String::trim) + .collect(Collectors.toList()); + } +}
Java
`Utils์„ฑ ํด๋ž˜์Šค`๋Š” ์ผ๋ฐ˜์ ์œผ๋กœ ์ •๋ง ์œ ํ‹ธ๋ฆฌํ‹ฐํ•œ ๊ฒƒ๋“ค๋งŒ ๊ธฐ๋Šฅ์„ ๋‹ด๋Š” ๊ฒƒ์ด ์ผ๋ฐ˜์ ์ด์—์š”. ํ˜„์žฌ ์œ ํ‹ธ๋กœ์ง์ด Y/N์ด๋ผ๋Š” ์–ด๋–ค ๋ฃฐ์— ๋Œ€ํ•ด์„œ ๋„ˆ๋ฌด ๋งŽ์ด ์•Œ๊ณ  ์žˆ๋Š” ์ƒํƒœ์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค ๋„๋ฉ”์ธ ํ˜น์€ DTO์˜ ๋กœ์ง์œผ๋กœ ๋ณ€๊ฒฝํ•˜๋Š” ๊ฒƒ์ด ์ข‹์•„๋ณด์ด๊ณ , Util์—์„œ ์‚ฌ์šฉํ•˜์‹ ๋‹ค๋ฉด ๊ฒ€์ฆ ๋Œ€์ƒ์ด ๋˜๋Š” Y/N๋„ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ๋ฐ›๋Š”๋‹ค๋ฉด ์กฐ๊ธˆ ๋” ๋ฒ”์šฉ์ ์œผ๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ๋ฉ”์†Œ๋“œ๊ฐ€ ๋  ๊ฒƒ ๊ฐ™์•„์š”.
@@ -0,0 +1,32 @@ +package blackjack.domain.card; + +import blackjack.domain.card.strategy.DrawStrategy; +import blackjack.domain.card.strategy.RandomDrawStrategy; +import lombok.Getter; + +import java.util.LinkedList; +import java.util.List; + +public class Deck { + + private static final String ALERT_NO_CARD_LEFT = "์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์นด๋“œ๋ฅผ ๋ชจ๋‘ ์†Œ์ง„ํ•˜์˜€์Šต๋‹ˆ๋‹ค."; + + @Getter + private final List<Card> deck; + + public Deck() { + this.deck = new LinkedList<>(DeckFactory.createDeck()); + } + + public Card drawCard() { + if (deck.isEmpty()) { + throw new RuntimeException(ALERT_NO_CARD_LEFT); + } + return deck.remove(generateNextDrawCardIndex(new RandomDrawStrategy())); + } + + private int generateNextDrawCardIndex(DrawStrategy drawStrategy) { + return drawStrategy.getNextIndex(deck); + } + +}
Java
LinkedList๋กœ ์„ ์–ธํ•˜์‹  ์ด์œ ๋Š” ์นด๋“œ๋ฅผ ํ•œ์žฅ์”ฉ ์‚ญ์ œํ•  ๋•Œ ArrayList๊ฐ€ ๋น„ํšจ์œจ์ ์ด๋ผ์„œ ๊ทธ๋ ‡๊ฒŒ ํ•˜์‹ ๊ฑธ๊นŒ์š”? ๐Ÿ‘
@@ -0,0 +1,32 @@ +package blackjack.domain.card; + +import blackjack.domain.card.strategy.DrawStrategy; +import blackjack.domain.card.strategy.RandomDrawStrategy; +import lombok.Getter; + +import java.util.LinkedList; +import java.util.List; + +public class Deck { + + private static final String ALERT_NO_CARD_LEFT = "์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์นด๋“œ๋ฅผ ๋ชจ๋‘ ์†Œ์ง„ํ•˜์˜€์Šต๋‹ˆ๋‹ค."; + + @Getter + private final List<Card> deck; + + public Deck() { + this.deck = new LinkedList<>(DeckFactory.createDeck()); + } + + public Card drawCard() { + if (deck.isEmpty()) { + throw new RuntimeException(ALERT_NO_CARD_LEFT); + } + return deck.remove(generateNextDrawCardIndex(new RandomDrawStrategy())); + } + + private int generateNextDrawCardIndex(DrawStrategy drawStrategy) { + return drawStrategy.getNextIndex(deck); + } + +}
Java
ํ˜„์žฌ๋Š” ๊ฒฝ๊ธฐ๋„์ค‘์— ์นด๋“œ๊ฐ€ ๋ชจ๋‘ ์†Œ์ง„๋˜๋ฉด, ํ”„๋กœ๊ทธ๋žจ์ด ์ข…๋ฃŒ๋˜๋Š” ๊ตฌ์กฐ์ธ๋ฐ์š”. ์ผ๋ฐ˜์ ์œผ๋กœ ๊ฒฝ๊ธฐ๋ฅผ ํ•˜๋‹ค, ์นด๋“œ๊ฐ€ ๋ชจ๋‘ ์†Œ์ง„๋œ๋‹ค๊ณ  ๊ทธ ๊ฒŒ์ž„์ด ๋ฌดํšจ๊ฐ€ ๋˜์ง€ ์•Š๋“ฏ์ด ์กฐ๊ธˆ ๋” ๊ตฌ์ฒด์ ์ธ ๋ฐฉ๋ฒ•/๊ตฌํ˜„์„ ๊ณ ๋ฏผํ•ด๋ณด๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”. (๊ตฌํ˜„์€ ํ•˜์ง€ ์•Š์œผ์…”๋„ ๋ฉ๋‹ˆ๋‹ค) ๋„๋ฉ”์ธ์— ๋Œ€ํ•ด์„œ ์กฐ๊ธˆ ๋” ๋Šฅ๋™์ ์œผ๋กœ ์ดํ•ดํ•˜๋ฉด ์–ด๋–จ๊นŒ ๋ผ๋Š” ์˜๋ฏธ์—์„œ ๋“œ๋ฆฐ ํ”ผ๋“œ๋ฐฑ์ž…๋‹ˆ๋‹ค. (์ฐธ๊ณ ๋กœ ๋ธ”๋ž™์žญ์—์„œ๋Š” ์ฐธ๊ฐ€ ์ธ์›์„ ์ œํ•œํ•˜๊ณ  ์žˆ๋”๋ผ๊ตฌ์š”๐Ÿ™‚)
@@ -0,0 +1,32 @@ +package blackjack.domain.card; + +import blackjack.domain.card.strategy.DrawStrategy; +import blackjack.domain.card.strategy.RandomDrawStrategy; +import lombok.Getter; + +import java.util.LinkedList; +import java.util.List; + +public class Deck { + + private static final String ALERT_NO_CARD_LEFT = "์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์นด๋“œ๋ฅผ ๋ชจ๋‘ ์†Œ์ง„ํ•˜์˜€์Šต๋‹ˆ๋‹ค."; + + @Getter + private final List<Card> deck; + + public Deck() { + this.deck = new LinkedList<>(DeckFactory.createDeck()); + } + + public Card drawCard() { + if (deck.isEmpty()) { + throw new RuntimeException(ALERT_NO_CARD_LEFT); + } + return deck.remove(generateNextDrawCardIndex(new RandomDrawStrategy())); + } + + private int generateNextDrawCardIndex(DrawStrategy drawStrategy) { + return drawStrategy.getNextIndex(deck); + } + +}
Java
Randomํ•œ ๊ฐ’์„ ํ…Œ์ŠคํŠธํ•˜๊ธฐ ์œ„ํ•ด์„œ, ๋ ˆ์ด์‹ฑ์นด์—์„œ ํ–ˆ๋˜ ๋ฐฉ์‹์œผ๋กœ ์ด๋ฅผ ์™ธ๋ถ€์—์„œ ์ฃผ์ž…๋ฐ›๋Š” ํ˜•ํƒœ๋กœ ํ•˜๋ฉด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,39 @@ +package blackjack.domain.card; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class DeckFactory { + + private static final List<Card> cardsDeck; + + static { + cardsDeck = createCardsDeck(); + } + + private static List<Card> createCardsDeck() { + List<Card> cards = new ArrayList<>(); + + for (Denomination denomination : Denomination.values()) { + cards.addAll(createCards(denomination)); + } + return cards; + } + + private static List<Card> createCards(Denomination denomination) { + List<Card> cards = new ArrayList<>(); + + for (Type type : Type.values()) { + cards.add(new Card(denomination, type)); + } + + return cards; + } + + public static List<Card> createDeck() { + return Collections.unmodifiableList(cardsDeck); + } +} + +
Java
์Šคํƒœํ‹ฑํ•˜๊ฒŒ ์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜์ด ์‹œ์ž‘๋จ๊ณผ ๋™์‹œ์— ์ƒ๊ธด๋‹ค๋Š” ๊ฒƒ์„ ๋ช…์‹œ์ ์œผ๋กœ ํ•˜๊ธฐ ์œ„ํ•ด์„œ static { } ํ˜•ํƒœ๋กœ ์ดˆ๊ธฐํ™”๋ฅผ ํ•  ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค๐Ÿ™‚
@@ -0,0 +1,39 @@ +package blackjack.domain.card; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class DeckFactory { + + private static final List<Card> cardsDeck; + + static { + cardsDeck = createCardsDeck(); + } + + private static List<Card> createCardsDeck() { + List<Card> cards = new ArrayList<>(); + + for (Denomination denomination : Denomination.values()) { + cards.addAll(createCards(denomination)); + } + return cards; + } + + private static List<Card> createCards(Denomination denomination) { + List<Card> cards = new ArrayList<>(); + + for (Type type : Type.values()) { + cards.add(new Card(denomination, type)); + } + + return cards; + } + + public static List<Card> createDeck() { + return Collections.unmodifiableList(cardsDeck); + } +} + +
Java
๋ฉ”์†Œ๋“œ์˜ ๋„ค์ด๋ฐ์œผ๋กœ ๋ดค์„ ๋•Œ `Deck` ์„ ๋งŒ๋“ค ๊ฒƒ ๊ฐ™์€๋ฐ, List<Card> ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ณ  ์žˆ๋Š” ๋ถ€๋ถ„์ด ์ง๊ด€์ ์œผ๋กœ ์ดํ•ด๋˜์ง€ ์•Š๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์ถ”๊ฐ€๋กœ ์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜์ด ๋œธ๊ณผ ๋™์‹œ์— `cardDecks`๋ฅผ ๋งŒ๋“ค๊ณ  ์žˆ์–ด์„œ, ์‚ฌ์šฉํ•œ๋‹ค๋ฉด getter ํ˜•ํƒœ๋กœ ์‚ฌ์šฉํ•ด์•ผํ•˜์ง€ ์•Š์„๊นŒ ์‹ถ๋„ค์š”. ํ˜น์‹œ ์ด ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ์‚ฌ๋žŒ ์ž…์žฅ์—์„œ๋Š” `์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜์—์„œ ํ•ด๋‹น ๊ฐ’(List<Card>)์€ ํ•ญ์ƒ ๊ณ ์ •๋˜์–ด ์žˆ๋‹ค๋ผ๋Š”๊ฑธ ๋ชฐ๋ผ๋„ ๋˜๊ณ  ํ•„์š”ํ•  ๋•Œ ๋‹ฌ๋ผํ•˜๋ฉด ๋œ๋‹ค` ๋А๋‚Œ์œผ๋กœ ์ž‘์„ฑํ•˜์‹ ๊ฑธ๊นŒ์š”? > ์š” ๊ฒฝ์šฐ์—๋„ ์‚ฌ์šฉ์ž ์ž…์žฅ์—์„  ํ•ญ์ƒ ๋ฑ์„ ๋งŒ๋“ค๊ฑฐ๋ผ ์˜ˆ์ƒํ•˜๊ณ  ๋กœ์ง์„ ์ง„ํ–‰ํ•  ์ˆ˜ ์žˆ์–ด์„œ ์œ„ํ—˜ํ•  ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,38 @@ +package blackjack.domain.card; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class CardTest { + + @DisplayName("์นด๋“œ ๊ฐ์ฒด์˜ ์ˆซ์ž์™€ ์ข…๋ฅ˜๊ฐ’์ด ๊ฐ™์œผ๋ฉด ๊ฐ™์€ ๊ฐ์ฒด๋กœ ํŒ๋‹จํ•œ๋‹ค") + @Test + void equalsTest() { + //given, when, then + assertThat(new Card(Denomination.TWO, Type.DIAMOND)) + .isEqualTo(new Card(Denomination.TWO, Type.DIAMOND)); + + } + + @DisplayName("์นด๋“œ ๊ฐ์ฒด์˜ ์ˆซ์ž์™€ ์ข…๋ฅ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค") + @Test + void printCardTwoDiamond() { + //given + Card card = new Card(Denomination.TWO, Type.DIAMOND); + + //when, then + assertThat(card).hasToString("2๋‹ค์ด์•„๋ชฌ๋“œ"); + } + + @DisplayName("์นด๋“œ ๊ฐ์ฒด์˜ ์ˆซ์ž์™€ ์ข…๋ฅ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค") + @Test + void printCardAceHeart() { + //given + Card card = new Card(Denomination.ACE, Type.HEART); + + //when, then + assertThat(card.toString()).isEqualTo("Aํ•˜ํŠธ"); + } +}
Java
`assertThat(card).hasToString("2๋‹ค์ด์•„๋ชฌ๋“œ")` ์ด๋Ÿฐ ๋ฌธ๋ฒ•๋„ ์žˆ์Šต๋‹ˆ๋‹ค๐Ÿ™‚
@@ -0,0 +1,102 @@ +package blackjack.domain.participant; + +import blackjack.domain.card.Card; +import blackjack.domain.card.Denomination; +import lombok.Getter; +import org.apache.commons.lang3.StringUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +@Getter +public abstract class Participant { + private static final int DIFFERENCE_OF_ACE_SCORE = 10; + private static final int BLACKJACK = 21; + private static final int ZERO = 0; + private static final String CHECK_NULL_OR_EMPTY = "์ด๋ฆ„์ด ๋นˆ ์นธ ํ˜น์€ null ๊ฐ’์ด ์•„๋‹Œ์ง€ ํ™•์ธํ•ด์ฃผ์„ธ์š”."; + private static final String CHECK_CONTAINING_ONLY_LETTERS_AND_DIGITS = "์ด๋ฆ„์€ ํŠน์ˆ˜๋ฌธ์ž๋ฅผ ํฌํ•จํ•˜์ง€ ์•Š์€ ๋ฌธ์ž์™€ ์ˆซ์ž๋กœ ์ง€์ •ํ•ด์ฃผ์„ธ์š”."; + + private final String name; + private final List<Card> cards; + + protected Participant(String name) { + validateName(name); + + this.name = name; + this.cards = new ArrayList<>(); + } + + private void validateName(String name) { + validateNullOrEmpty(name); + validateAlphaNumeric(name); + } + + private void validateNullOrEmpty(String name) { + if (StringUtils.isBlank(name)) { + throw new IllegalArgumentException(CHECK_NULL_OR_EMPTY); + } + } + + private void validateAlphaNumeric(String name) { + if (!StringUtils.isAlphanumericSpace(name)) { + throw new IllegalArgumentException(CHECK_CONTAINING_ONLY_LETTERS_AND_DIGITS); + } + } + + protected abstract boolean drawable(); + + public void receiveCard(Card card) { + cards.add(card); + } + + public int getCardsSum() { + int scoreOfAceAsEleven = sumOfCardsScore(); + int aceCount = getAceCount(); + + while (canCountAceAsOne(scoreOfAceAsEleven, aceCount)) { + scoreOfAceAsEleven = scoreOfAceAsOne(scoreOfAceAsEleven); + aceCount--; + } + + return scoreOfAceAsEleven; + } + + private int scoreOfAceAsOne(int scoreOfAceAsEleven) { + return scoreOfAceAsEleven - DIFFERENCE_OF_ACE_SCORE; + } + + private boolean canCountAceAsOne(int scoreOfAceAsEleven, int aceCount) { + return scoreOfAceAsEleven > BLACKJACK && aceCount > ZERO; + } + + private int getAceCount() { + return (int) cards.stream() + .filter(Card::isAce) + .count(); + } + + private int sumOfCardsScore() { + return cards.stream() + .map(Card::getDenomination) + .mapToInt(Denomination::getScore) + .sum(); + } + + public boolean isBust() { + return getCardsSum() > BLACKJACK; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Participant that = (Participant) o; + return Objects.equals(name, that.name) && Objects.equals(cards, that.cards); + } + + @Override + public int hashCode() { + return Objects.hash(name, cards); + } +}
Java
ACE์˜ ์ˆ˜๋ฅผ ๊ฒฐ์ •ํ•  ๋•Œ, 1 ๋˜๋Š” 11์ด ๋˜๋Š” ๋กœ์ง์€ Denomination์˜ ์—ญํ• ์ด ์•„๋‹๊นŒ์š”?
@@ -0,0 +1,27 @@ +package blackjack.domain.participant; + +import lombok.Getter; + +@Getter +public class Player extends Participant { + + private static final int PLAYER_DRAW_THRESHOLD = 21; + private static final String DEALER_NAME = "๋”œ๋Ÿฌ"; + private static final String CHECK_SAME_NAME_AS_DEALER = "์ด๋ฆ„์€ ๋”œ๋Ÿฌ์™€ ๊ฐ™์„ ์ˆ˜ ์—†์œผ๋‹ˆ ๋‹ค๋ฅธ ์ด๋ฆ„์„ ์ง€์ •ํ•ด์ฃผ์„ธ์š”."; + + public Player(String name) { + super(name); + validateDealerNameDuplicated(name); + } + + private void validateDealerNameDuplicated(String name) { + if (name.equals(DEALER_NAME)) { + throw new IllegalArgumentException(CHECK_SAME_NAME_AS_DEALER); + } + } + + @Override + public boolean drawable() { + return getCardsSum() < PLAYER_DRAW_THRESHOLD; + } +}
Java
์žฌ๋ฐŒ๋Š” ์ œ์•ฝ์‚ฌํ•ญ์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค๐Ÿ™‚
@@ -0,0 +1,27 @@ +package blackjack.domain.participant; + +import lombok.Getter; + +@Getter +public class Player extends Participant { + + private static final int PLAYER_DRAW_THRESHOLD = 21; + private static final String DEALER_NAME = "๋”œ๋Ÿฌ"; + private static final String CHECK_SAME_NAME_AS_DEALER = "์ด๋ฆ„์€ ๋”œ๋Ÿฌ์™€ ๊ฐ™์„ ์ˆ˜ ์—†์œผ๋‹ˆ ๋‹ค๋ฅธ ์ด๋ฆ„์„ ์ง€์ •ํ•ด์ฃผ์„ธ์š”."; + + public Player(String name) { + super(name); + validateDealerNameDuplicated(name); + } + + private void validateDealerNameDuplicated(String name) { + if (name.equals(DEALER_NAME)) { + throw new IllegalArgumentException(CHECK_SAME_NAME_AS_DEALER); + } + } + + @Override + public boolean drawable() { + return getCardsSum() < PLAYER_DRAW_THRESHOLD; + } +}
Java
ํ˜„์žฌ ์‚ฌ์šฉํ•˜์‹  ์ด์œ ๋Š” OutputView ๋กœ์ง์„ ๋‹จ์ˆœํ•˜๊ฒŒ ํ•˜๊ธฐ ์œ„ํ•จ์ธ ๊ฒƒ ๊ฐ™์•„์š”. ํ™”๋ฉด์— ๋ณด์—ฌ์ฃผ๋Š” ํ˜•ํƒœ๊ฐ€ ๋‹ฌ๋ผ์กŒ์„ ๋•Œ, ๋„๋ฉ”์ธ์„ ์ˆ˜์ •ํ•ด์•ผ ํ•œ๋‹ค๋ฉด ์˜์กด๊ด€๊ณ„๊ฐ€ ์ž˜ ๋ชป ์„ค๊ณ„๋œ๊ฑฐ๋ผ๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,27 @@ +package blackjack.domain.participant; + +import lombok.Getter; + +@Getter +public class Player extends Participant { + + private static final int PLAYER_DRAW_THRESHOLD = 21; + private static final String DEALER_NAME = "๋”œ๋Ÿฌ"; + private static final String CHECK_SAME_NAME_AS_DEALER = "์ด๋ฆ„์€ ๋”œ๋Ÿฌ์™€ ๊ฐ™์„ ์ˆ˜ ์—†์œผ๋‹ˆ ๋‹ค๋ฅธ ์ด๋ฆ„์„ ์ง€์ •ํ•ด์ฃผ์„ธ์š”."; + + public Player(String name) { + super(name); + validateDealerNameDuplicated(name); + } + + private void validateDealerNameDuplicated(String name) { + if (name.equals(DEALER_NAME)) { + throw new IllegalArgumentException(CHECK_SAME_NAME_AS_DEALER); + } + } + + @Override + public boolean drawable() { + return getCardsSum() < PLAYER_DRAW_THRESHOLD; + } +}
Java
ํ•ด๋‹น ๋ฉ”์†Œ๋“œ๋Š” ์ด๊ฒผ๋‹ค๊ฐ€, ์•„๋‹ˆ๋ผ `๊ฒฝ๊ธฐ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜ํ™˜ํ•ด์ฃผ๋Š” ๋ฉ”์†Œ๋“œ`๋‹ˆ๊นŒ ์ด๋ฆ„์„ ๋ณ€๊ฒฝํ•ด์ฃผ์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์ถ”๊ฐ€๋กœ `Rule`์ด ์‚ฌ์šฉ์ž์™€ ๋”œ๋Ÿฌ๋ฅผ ๋ชจ๋‘ ๋ฐ›์•„ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜ํ™˜ํ•ด์ฃผ๋Š”๊ฒŒ ์—ญํ• ์ด ์ ์ ˆํ•˜์ง€ ์•Š์„๊นŒ์š”? (ํ˜„์žฌ์˜ rule.compare๊ณผ getWinningResult๋ฅผ ํ•ฉ์นœ ๋ฉ”์†Œ๋“œ๋ฅผ Rule์—์„œ ์ œ๊ณตํ•˜๋ฉด ์–ด๋–จ๊นŒ์š”?)
@@ -0,0 +1,27 @@ +package blackjack.domain.participant; + +import lombok.Getter; + +@Getter +public class Player extends Participant { + + private static final int PLAYER_DRAW_THRESHOLD = 21; + private static final String DEALER_NAME = "๋”œ๋Ÿฌ"; + private static final String CHECK_SAME_NAME_AS_DEALER = "์ด๋ฆ„์€ ๋”œ๋Ÿฌ์™€ ๊ฐ™์„ ์ˆ˜ ์—†์œผ๋‹ˆ ๋‹ค๋ฅธ ์ด๋ฆ„์„ ์ง€์ •ํ•ด์ฃผ์„ธ์š”."; + + public Player(String name) { + super(name); + validateDealerNameDuplicated(name); + } + + private void validateDealerNameDuplicated(String name) { + if (name.equals(DEALER_NAME)) { + throw new IllegalArgumentException(CHECK_SAME_NAME_AS_DEALER); + } + } + + @Override + public boolean drawable() { + return getCardsSum() < PLAYER_DRAW_THRESHOLD; + } +}
Java
`๋กœ์ง์ƒ ์—†์„ ์ˆ˜๊ฐ€ ์—†๋‹ค` ๋ผ๋Š” ์ƒ๊ฐ์œผ๋กœ `get`์„ ์‚ฌ์šฉํ•ด์ฃผ์‹  ๊ฒƒ ๊ฐ™์•„์š”. ๋‹ค๋งŒ ์š”๊ฒŒ ์—†๋Š” ๊ฒฝ์šฐ์—๋Š” `NullPoint`๊ฐ€ ๋‚ ํ…๋ฐ์š”. ์ด ๋ฉ”์‹œ์ง€๋ฅผ ๋ณด๊ณ  ์–ด๋–ค ์˜๋ฏธ์ธ์ง€ ์ฐพ๊ธฐ๊ฐ€ ์–ด๋ ค์šธ ๊ฒƒ ๊ฐ™์•„์š”. ์š”๋ ‡๊ฒŒ ์• ๋งคํ•œ ๊ฒฝ์šฐ์— ์ €๋Š” orElseThrow๋ฅผ ํ•œ๋‹ค๊ฑฐ๋‚˜, ๋กœ๊ทธ๋ฅผ ํ†ตํ•ด์„œ ํ”„๋กœ๊ทธ๋žจ ์ž์ฒด๊ฐ€ ์ž˜๋ชป๋˜์—ˆ์Œ์„ ์•Œ๋ ค์ฃผ๋Š” ํ˜•ํƒœ๋กœ ๋‚จ๊ธฐ๋Š” ํŽธ์ด์—์š”.
@@ -0,0 +1,50 @@ +package blackjack.domain.result; + +import blackjack.domain.participant.Dealer; +import blackjack.domain.participant.Player; +import lombok.Getter; + +import java.util.Arrays; +import java.util.function.BiFunction; + +public enum Rule{ + // ์นด๋“œ ๊ฐ’์˜ ํ•ฉ์ด 21์„ ๋„˜์œผ๋ฉด ์ŠนํŒจ ๊ฒฐ์ • (ํ”Œ๋ ˆ์ด์–ด ๊ธฐ์ค€์œผ๋กœ ์„ ์–ธ) + PLAYER_BUST(((player, dealer) -> player.isBust()), WinningResult.LOSE, 1), + DEALER_BUST(((player, dealer) -> dealer.isBust()), WinningResult.WIN, 2), + + // ์นด๋“œ ๊ฐ’์˜ ํ•ฉ์ด 21์„ ๋„˜์ง€ ์•Š์œผ๋ฉด์„œ, ๊ฐ’์ด ๋” ํฐ์ชฝ์ด ์ŠนํŒจ๊ฒฐ์ •(์ด๋ฏธ ์—ฌ๊ธฐ์„œ ๊ฒฐ์ •, BlackJack ์ฒดํฌ ํ•„์š”์—†์Œ) + PLAYER_HIGHER(((player, dealer) -> player.getCardsSum() > dealer.getCardsSum()), WinningResult.WIN, 3), + DEALER_HIGHER(((player, dealer) -> player.getCardsSum() < dealer.getCardsSum()), WinningResult.LOSE, 4), + + // ๋ฌด์Šน๋ถ€ ๊ฒฐ์ • + TIES(((player, dealer) -> player.getCardsSum() == dealer.getCardsSum()), WinningResult.TIE, 5); + + private BiFunction<Player, Dealer, Boolean> compare; + private WinningResult winningResult; + @Getter + private int verificationOrder; + + Rule(BiFunction<Player, Dealer, Boolean> compare, WinningResult winningResult, int verificationOrder) { + this.compare = compare; + this.winningResult = winningResult; + this.verificationOrder = verificationOrder; + } + + public Boolean findMatchingRule(Player player, Dealer dealer) { + return compare.apply(player, dealer); + } + + public WinningResult getWinningResult() { + return winningResult; + } + + public static WinningResult resultPlayerVersusDealer(Player player, Dealer dealer) { + + return Arrays.stream(Rule.values()) + .sorted(new RuleComparator()) + .filter(rule -> rule.findMatchingRule(player, dealer)) + .findFirst() + .orElseThrow(() -> new RuntimeException("์ผ์น˜ํ•˜๋Š” ๊ฒฐ๊ณผ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")) + .getWinningResult(); + } +}
Java
์š” ๋กœ์ง๋“ค์ด ์ˆœ์„œ์— ๋”ฐ๋ผ ์˜ํ–ฅ์„ ๋ฐ›์„ ๊ฒƒ ๊ฐ™์•„์š”. `์›๋ž˜๋Š” ํ”Œ๋ ˆ์ด์–ด๊ฐ€ ๋ฒ„์ŠคํŠธ์ธ ๊ฒฝ์šฐ ํ•ญ์ƒ ํŒจ๋ฐฐ๋กœ ๊ฐ„์ฃผ๋˜๋Š”๋ฐ ๋ฌด์Šน๋ถ€ Enum์„ ๋งจ ์œ„๋กœ ์˜ฌ๋ฆฌ๋ฉด, ๋น„๊ธด๊ฑฐ๋กœ ๊ฐ„์ฃผ๋˜๋Š” ํ˜•์‹`์œผ๋กœ์—ฌ! ๊ทธ๋ ‡๋‹ค๋ฉด ๊ธฐ์กด `Enum์˜ ์ˆœ์„œ๊ฐ€ ์ค‘์š”ํ•˜๋‹ค`๋Š” ๊ฒƒ์„ ๋ช…์‹œ์ ์œผ๋กœ ๋“œ๋Ÿฌ๋‚ด๊ฑฐ๋‚˜, ๋‹ค๋ฅธ ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•ด์ค˜์•ผ ๋‹ค๋ฅธ ์‚ฌ๋žŒ์ด ์‹ค์ˆ˜ํ•  ์—ฌ์ง€๋ฅผ ์ค„์ผ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”ใ…Žใ…Ž(์—ฌ๊ธด ๊ฐ€์žฅ ์ค‘์š”ํ•œ ๋กœ์ง์ด๋‹ˆ๊นŒ ๋”๋”์šฑ์ด์š”!)
@@ -0,0 +1,50 @@ +package blackjack.domain.result; + +import blackjack.domain.participant.Dealer; +import blackjack.domain.participant.Player; +import lombok.Getter; + +import java.util.Arrays; +import java.util.function.BiFunction; + +public enum Rule{ + // ์นด๋“œ ๊ฐ’์˜ ํ•ฉ์ด 21์„ ๋„˜์œผ๋ฉด ์ŠนํŒจ ๊ฒฐ์ • (ํ”Œ๋ ˆ์ด์–ด ๊ธฐ์ค€์œผ๋กœ ์„ ์–ธ) + PLAYER_BUST(((player, dealer) -> player.isBust()), WinningResult.LOSE, 1), + DEALER_BUST(((player, dealer) -> dealer.isBust()), WinningResult.WIN, 2), + + // ์นด๋“œ ๊ฐ’์˜ ํ•ฉ์ด 21์„ ๋„˜์ง€ ์•Š์œผ๋ฉด์„œ, ๊ฐ’์ด ๋” ํฐ์ชฝ์ด ์ŠนํŒจ๊ฒฐ์ •(์ด๋ฏธ ์—ฌ๊ธฐ์„œ ๊ฒฐ์ •, BlackJack ์ฒดํฌ ํ•„์š”์—†์Œ) + PLAYER_HIGHER(((player, dealer) -> player.getCardsSum() > dealer.getCardsSum()), WinningResult.WIN, 3), + DEALER_HIGHER(((player, dealer) -> player.getCardsSum() < dealer.getCardsSum()), WinningResult.LOSE, 4), + + // ๋ฌด์Šน๋ถ€ ๊ฒฐ์ • + TIES(((player, dealer) -> player.getCardsSum() == dealer.getCardsSum()), WinningResult.TIE, 5); + + private BiFunction<Player, Dealer, Boolean> compare; + private WinningResult winningResult; + @Getter + private int verificationOrder; + + Rule(BiFunction<Player, Dealer, Boolean> compare, WinningResult winningResult, int verificationOrder) { + this.compare = compare; + this.winningResult = winningResult; + this.verificationOrder = verificationOrder; + } + + public Boolean findMatchingRule(Player player, Dealer dealer) { + return compare.apply(player, dealer); + } + + public WinningResult getWinningResult() { + return winningResult; + } + + public static WinningResult resultPlayerVersusDealer(Player player, Dealer dealer) { + + return Arrays.stream(Rule.values()) + .sorted(new RuleComparator()) + .filter(rule -> rule.findMatchingRule(player, dealer)) + .findFirst() + .orElseThrow(() -> new RuntimeException("์ผ์น˜ํ•˜๋Š” ๊ฒฐ๊ณผ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")) + .getWinningResult(); + } +}
Java
์นœ์ ˆํ•œ ์ฃผ์„ ์ข‹๋„ค์š”. ํ•ด๋‹น ๋ฉ”์†Œ๋“œ๋Š” participant์—๊ฒŒ ๊ฐ’์„ ๋น„๊ตํ•˜๋Š” ํ˜•ํƒœ๋กœ ๋ฆฌํŒฉํ† ๋งํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”
@@ -0,0 +1,50 @@ +package blackjack.domain.result; + +import blackjack.domain.participant.Dealer; +import blackjack.domain.participant.Player; +import lombok.Getter; + +import java.util.Arrays; +import java.util.function.BiFunction; + +public enum Rule{ + // ์นด๋“œ ๊ฐ’์˜ ํ•ฉ์ด 21์„ ๋„˜์œผ๋ฉด ์ŠนํŒจ ๊ฒฐ์ • (ํ”Œ๋ ˆ์ด์–ด ๊ธฐ์ค€์œผ๋กœ ์„ ์–ธ) + PLAYER_BUST(((player, dealer) -> player.isBust()), WinningResult.LOSE, 1), + DEALER_BUST(((player, dealer) -> dealer.isBust()), WinningResult.WIN, 2), + + // ์นด๋“œ ๊ฐ’์˜ ํ•ฉ์ด 21์„ ๋„˜์ง€ ์•Š์œผ๋ฉด์„œ, ๊ฐ’์ด ๋” ํฐ์ชฝ์ด ์ŠนํŒจ๊ฒฐ์ •(์ด๋ฏธ ์—ฌ๊ธฐ์„œ ๊ฒฐ์ •, BlackJack ์ฒดํฌ ํ•„์š”์—†์Œ) + PLAYER_HIGHER(((player, dealer) -> player.getCardsSum() > dealer.getCardsSum()), WinningResult.WIN, 3), + DEALER_HIGHER(((player, dealer) -> player.getCardsSum() < dealer.getCardsSum()), WinningResult.LOSE, 4), + + // ๋ฌด์Šน๋ถ€ ๊ฒฐ์ • + TIES(((player, dealer) -> player.getCardsSum() == dealer.getCardsSum()), WinningResult.TIE, 5); + + private BiFunction<Player, Dealer, Boolean> compare; + private WinningResult winningResult; + @Getter + private int verificationOrder; + + Rule(BiFunction<Player, Dealer, Boolean> compare, WinningResult winningResult, int verificationOrder) { + this.compare = compare; + this.winningResult = winningResult; + this.verificationOrder = verificationOrder; + } + + public Boolean findMatchingRule(Player player, Dealer dealer) { + return compare.apply(player, dealer); + } + + public WinningResult getWinningResult() { + return winningResult; + } + + public static WinningResult resultPlayerVersusDealer(Player player, Dealer dealer) { + + return Arrays.stream(Rule.values()) + .sorted(new RuleComparator()) + .filter(rule -> rule.findMatchingRule(player, dealer)) + .findFirst() + .orElseThrow(() -> new RuntimeException("์ผ์น˜ํ•˜๋Š” ๊ฒฐ๊ณผ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")) + .getWinningResult(); + } +}
Java
ํ•ด๋‹น ๋ฉ”์†Œ๋“œ๋Š” ๋น„๊ตํ•˜๋Š” ๋ฉ”์†Œ๋“œ๊ฐ€ ์•„๋‹ˆ๋ผ, ์–ด๋–ค Rule์ธ์ง€๋ฅผ ์ฐพ๋Š”๊ฑฐ์— ๊ฐ€๊น๋„ค์š”. ์š”๊ฒƒ๋„ ๋ฉ”์†Œ๋“œ ์ด๋ฆ„ ์ˆ˜์ •ํ•ด์ฃผ์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”.
@@ -0,0 +1,27 @@ +package blackjack.domain.result; + +import lombok.Getter; + +@Getter +public enum WinningResult { + + WIN("์Šน"), + LOSE("ํŒจ"), + TIE("๋ฌด์Šน๋ถ€"); + + private final String result; + + WinningResult(String result) { + this.result = result; + } + + public WinningResult reverse() { + if (this == WIN) { + return LOSE; + } + if (this == LOSE) { + return WIN; + } + return TIE; + } +}
Java
์š”๊ฑฐ ์ œ๊ฐ€ ์ „์— ํ•  ๋•Œ, ์•ˆ ๋๋˜๊ฑด๋ฐ WinningResult๊ฐ€ WinningResult ๋ฉค๋ฒ„๋ณ€์ˆ˜๋ฅผ ๊ฐ€์ง€๊ณ , ๋ฐ˜๋Œ€๋กœ ์„ ์–ธํ•˜๋ฉด ์•ˆ๋˜๋”๋ผ๊ตฌ์š”. ์™œ ์•ˆ๋˜๋Š”์ง€ ๋ฐ”๋กœ ์ดํ•ด๊ฐ€์‹œ๋ฉด Enum์„ ์ž˜ ์ดํ•ดํ•˜๊ณ  ๊ณ„์‹  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹คใ…‹ใ…‹ใ…‹ ```java WIN("์Šน", LOST) // ์š”๋Ÿฐ์‹์œผ๋กœ์—ฌ ```
@@ -0,0 +1,66 @@ +package blackjack.controller; + +import blackjack.domain.card.Deck; +import blackjack.domain.participant.Dealer; +import blackjack.domain.participant.Player; +import blackjack.domain.participant.PlayersFactory; +import blackjack.domain.result.GameResult; +import blackjack.dto.DrawCardRequestDto; +import blackjack.dto.PlayersNameInputDto; +import blackjack.view.InputView; +import blackjack.view.OutputView; + +import java.util.List; + +public class BlackJackController { + private final InputView inputView = new InputView(); + private final OutputView outputView = new OutputView(); + + public void run() { + PlayersNameInputDto namesInput = inputView.getPlayersName(); + Dealer dealer = new Dealer(); + Deck deck = new Deck(); + List<Player> players = PlayersFactory.createPlayers(namesInput.getPlayersName()); + + drawTowCards(dealer, players, deck); + drawCardToPlayers(players, deck); + drawCardToDealer(dealer, deck); + outputView.printCardsResult(dealer, players); + outputView.printGameResult(GameResult.of(dealer, players)); + } + + private void drawTowCards(Dealer dealer, List<Player> players, Deck deck) { + for (Player player : players) { + player.receiveCard(deck.drawCard()); + player.receiveCard(deck.drawCard()); + } + dealer.receiveCard(deck.drawCard()); + dealer.receiveCard(deck.drawCard()); + outputView.printFirstCardsGiven(players, dealer); + outputView.printDealerCard(dealer); + outputView.printPlayersCard(players); + } + + private void drawCardToPlayers(List<Player> players, Deck deck) { + for (Player player : players) { + drawCardToPlayer(player, deck); + } + } + + private void drawCardToPlayer(Player player, Deck deck) { + DrawCardRequestDto drawCardRequest = inputView.getPlayersResponse(player); + while (player.drawable() && drawCardRequest.isYes()) { + player.receiveCard(deck.drawCard()); + + outputView.printCards(player); + drawCardRequest = inputView.getPlayersResponse(player); + } + } + + private void drawCardToDealer(Dealer dealer, Deck deck) { + while (dealer.drawable()) { + dealer.receiveCard(deck.drawCard()); + outputView.printDealerCardGiven(); + } + } +}
Java
์—ฌ๋Ÿฌ๋ช…์ด ๋™์‹œ์— ์š”์ฒญํ•˜๋Š” ๊ฒฝ์šฐ๋ฅผ ๊ณ ๋ คํ•˜์ง€ ์•Š์•˜๋„ค์š”. ์„œ๋น„์Šค ๊ฐœ๋ฐœ์ž๋กœ์„œ ํ•ญ์ƒ ์ƒ๊ฐํ•ด์•ผ ํ•  ๋ถ€๋ถ„์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. view๋ฅผ ์ œ์™ธํ•œ ํด๋ž˜์Šค๋ณ€์ˆ˜๋“ค์„ ๋กœ์ปฌ๋ณ€์ˆ˜๋กœ ์ˆ˜์ •ํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,66 @@ +package blackjack.controller; + +import blackjack.domain.card.Deck; +import blackjack.domain.participant.Dealer; +import blackjack.domain.participant.Player; +import blackjack.domain.participant.PlayersFactory; +import blackjack.domain.result.GameResult; +import blackjack.dto.DrawCardRequestDto; +import blackjack.dto.PlayersNameInputDto; +import blackjack.view.InputView; +import blackjack.view.OutputView; + +import java.util.List; + +public class BlackJackController { + private final InputView inputView = new InputView(); + private final OutputView outputView = new OutputView(); + + public void run() { + PlayersNameInputDto namesInput = inputView.getPlayersName(); + Dealer dealer = new Dealer(); + Deck deck = new Deck(); + List<Player> players = PlayersFactory.createPlayers(namesInput.getPlayersName()); + + drawTowCards(dealer, players, deck); + drawCardToPlayers(players, deck); + drawCardToDealer(dealer, deck); + outputView.printCardsResult(dealer, players); + outputView.printGameResult(GameResult.of(dealer, players)); + } + + private void drawTowCards(Dealer dealer, List<Player> players, Deck deck) { + for (Player player : players) { + player.receiveCard(deck.drawCard()); + player.receiveCard(deck.drawCard()); + } + dealer.receiveCard(deck.drawCard()); + dealer.receiveCard(deck.drawCard()); + outputView.printFirstCardsGiven(players, dealer); + outputView.printDealerCard(dealer); + outputView.printPlayersCard(players); + } + + private void drawCardToPlayers(List<Player> players, Deck deck) { + for (Player player : players) { + drawCardToPlayer(player, deck); + } + } + + private void drawCardToPlayer(Player player, Deck deck) { + DrawCardRequestDto drawCardRequest = inputView.getPlayersResponse(player); + while (player.drawable() && drawCardRequest.isYes()) { + player.receiveCard(deck.drawCard()); + + outputView.printCards(player); + drawCardRequest = inputView.getPlayersResponse(player); + } + } + + private void drawCardToDealer(Dealer dealer, Deck deck) { + while (dealer.drawable()) { + dealer.receiveCard(deck.drawCard()); + outputView.printDealerCardGiven(); + } + } +}
Java
Dto ์ด๋ฆ„์„ DrawCardRequestDto๋กœ ๋ณ€๊ฒฝํ•˜๊ณ  ํŒ๋‹จ๋กœ์ง์„ Dto๋กœ ์ด๋™ํ–ˆ์Šต๋‹ˆ๋‹ค. Dto๊ฐ€ ๊ฐ€์ง„ ๋ฐ์ดํ„ฐ๋งŒ์„ ์ด์šฉํ•œ ๊ฐ„๋‹จํ•œ ๋กœ์ง์€ Dto์—์„œ ์ฒ˜๋ฆฌํ•ด๋„ ๋œ๋‹ค๋Š” ๊ฒƒ์„ ์•Œ๊ฒŒ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. Dto ์ด๋ฆ„์„ ๋ฐ›์•„์˜จ ๊ฒƒ์ธ์ง€, ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ์ธ์ง€์— ๋”ฐ๋ผ ํ†ต์ผํ•˜๋ฉด ์ผ๊ด€์„ฑ์ด ์žˆ์–ด ํ—ท๊ฐˆ๋ฆด ์ผ์ด ์—†์–ด์„œ ์ข‹์€ ๋ฐฉ๋ฒ•์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,17 @@ +package blackjack.utils; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class StringUtil { + private static final String COMMA = ","; + private static final String RESPONSE_RESTRICT_MESSAGE = "y ํ˜น์€ n ๋งŒ ์ž…๋ ฅํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค."; + + public static List<String> splitByComma(String input) { + List<String> names = Arrays.asList(input.split(COMMA)); + return names.stream() + .map(String::trim) + .collect(Collectors.toList()); + } +}
Java
๋กœ์ง์„ DrawCardRequestDto๋กœ ์ด๋™ํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,32 @@ +package blackjack.domain.card; + +import blackjack.domain.card.strategy.DrawStrategy; +import blackjack.domain.card.strategy.RandomDrawStrategy; +import lombok.Getter; + +import java.util.LinkedList; +import java.util.List; + +public class Deck { + + private static final String ALERT_NO_CARD_LEFT = "์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์นด๋“œ๋ฅผ ๋ชจ๋‘ ์†Œ์ง„ํ•˜์˜€์Šต๋‹ˆ๋‹ค."; + + @Getter + private final List<Card> deck; + + public Deck() { + this.deck = new LinkedList<>(DeckFactory.createDeck()); + } + + public Card drawCard() { + if (deck.isEmpty()) { + throw new RuntimeException(ALERT_NO_CARD_LEFT); + } + return deck.remove(generateNextDrawCardIndex(new RandomDrawStrategy())); + } + + private int generateNextDrawCardIndex(DrawStrategy drawStrategy) { + return drawStrategy.getNextIndex(deck); + } + +}
Java
๋„ต ๊ทธ๋ ‡์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,32 @@ +package blackjack.domain.card; + +import blackjack.domain.card.strategy.DrawStrategy; +import blackjack.domain.card.strategy.RandomDrawStrategy; +import lombok.Getter; + +import java.util.LinkedList; +import java.util.List; + +public class Deck { + + private static final String ALERT_NO_CARD_LEFT = "์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์นด๋“œ๋ฅผ ๋ชจ๋‘ ์†Œ์ง„ํ•˜์˜€์Šต๋‹ˆ๋‹ค."; + + @Getter + private final List<Card> deck; + + public Deck() { + this.deck = new LinkedList<>(DeckFactory.createDeck()); + } + + public Card drawCard() { + if (deck.isEmpty()) { + throw new RuntimeException(ALERT_NO_CARD_LEFT); + } + return deck.remove(generateNextDrawCardIndex(new RandomDrawStrategy())); + } + + private int generateNextDrawCardIndex(DrawStrategy drawStrategy) { + return drawStrategy.getNextIndex(deck); + } + +}
Java
DrawStrategy ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๋งŒ๋“ค๊ณ  ๊ทธ๊ฒƒ์„ ๊ตฌํ˜„ํ•˜๋Š” RandomDrawStrategy ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“ค์—ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,39 @@ +package blackjack.domain.card; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class DeckFactory { + + private static final List<Card> cardsDeck; + + static { + cardsDeck = createCardsDeck(); + } + + private static List<Card> createCardsDeck() { + List<Card> cards = new ArrayList<>(); + + for (Denomination denomination : Denomination.values()) { + cards.addAll(createCards(denomination)); + } + return cards; + } + + private static List<Card> createCards(Denomination denomination) { + List<Card> cards = new ArrayList<>(); + + for (Type type : Type.values()) { + cards.add(new Card(denomination, type)); + } + + return cards; + } + + public static List<Card> createDeck() { + return Collections.unmodifiableList(cardsDeck); + } +} + +
Java
์Šคํƒœํ‹ฑ๋ธ”๋ก์œผ๋กœ ๋ณ€๊ฒฝํ–ˆ์Šต๋‹ˆ๋‹ค. ๊ธฐ๋Šฅ์€ ๋“ฑํ˜ธ๋ฅผ ์‚ฌ์šฉํ•œ ์ฝ”๋“œ์™€ ์ •ํ™•ํžˆ ๋™์ผํ•œ๊ฑด๊ฐ€์š”?
@@ -0,0 +1,38 @@ +package blackjack.domain.card; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class CardTest { + + @DisplayName("์นด๋“œ ๊ฐ์ฒด์˜ ์ˆซ์ž์™€ ์ข…๋ฅ˜๊ฐ’์ด ๊ฐ™์œผ๋ฉด ๊ฐ™์€ ๊ฐ์ฒด๋กœ ํŒ๋‹จํ•œ๋‹ค") + @Test + void equalsTest() { + //given, when, then + assertThat(new Card(Denomination.TWO, Type.DIAMOND)) + .isEqualTo(new Card(Denomination.TWO, Type.DIAMOND)); + + } + + @DisplayName("์นด๋“œ ๊ฐ์ฒด์˜ ์ˆซ์ž์™€ ์ข…๋ฅ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค") + @Test + void printCardTwoDiamond() { + //given + Card card = new Card(Denomination.TWO, Type.DIAMOND); + + //when, then + assertThat(card).hasToString("2๋‹ค์ด์•„๋ชฌ๋“œ"); + } + + @DisplayName("์นด๋“œ ๊ฐ์ฒด์˜ ์ˆซ์ž์™€ ์ข…๋ฅ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค") + @Test + void printCardAceHeart() { + //given + Card card = new Card(Denomination.ACE, Type.HEART); + + //when, then + assertThat(card.toString()).isEqualTo("Aํ•˜ํŠธ"); + } +}
Java
assert๋ฌธ์œผ๋กœ ๋ฌธ์ž์—ด์„ ๋น„๊ตํ•  ๋•Œ๋Š” hasToString๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,102 @@ +package blackjack.domain.participant; + +import blackjack.domain.card.Card; +import blackjack.domain.card.Denomination; +import lombok.Getter; +import org.apache.commons.lang3.StringUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +@Getter +public abstract class Participant { + private static final int DIFFERENCE_OF_ACE_SCORE = 10; + private static final int BLACKJACK = 21; + private static final int ZERO = 0; + private static final String CHECK_NULL_OR_EMPTY = "์ด๋ฆ„์ด ๋นˆ ์นธ ํ˜น์€ null ๊ฐ’์ด ์•„๋‹Œ์ง€ ํ™•์ธํ•ด์ฃผ์„ธ์š”."; + private static final String CHECK_CONTAINING_ONLY_LETTERS_AND_DIGITS = "์ด๋ฆ„์€ ํŠน์ˆ˜๋ฌธ์ž๋ฅผ ํฌํ•จํ•˜์ง€ ์•Š์€ ๋ฌธ์ž์™€ ์ˆซ์ž๋กœ ์ง€์ •ํ•ด์ฃผ์„ธ์š”."; + + private final String name; + private final List<Card> cards; + + protected Participant(String name) { + validateName(name); + + this.name = name; + this.cards = new ArrayList<>(); + } + + private void validateName(String name) { + validateNullOrEmpty(name); + validateAlphaNumeric(name); + } + + private void validateNullOrEmpty(String name) { + if (StringUtils.isBlank(name)) { + throw new IllegalArgumentException(CHECK_NULL_OR_EMPTY); + } + } + + private void validateAlphaNumeric(String name) { + if (!StringUtils.isAlphanumericSpace(name)) { + throw new IllegalArgumentException(CHECK_CONTAINING_ONLY_LETTERS_AND_DIGITS); + } + } + + protected abstract boolean drawable(); + + public void receiveCard(Card card) { + cards.add(card); + } + + public int getCardsSum() { + int scoreOfAceAsEleven = sumOfCardsScore(); + int aceCount = getAceCount(); + + while (canCountAceAsOne(scoreOfAceAsEleven, aceCount)) { + scoreOfAceAsEleven = scoreOfAceAsOne(scoreOfAceAsEleven); + aceCount--; + } + + return scoreOfAceAsEleven; + } + + private int scoreOfAceAsOne(int scoreOfAceAsEleven) { + return scoreOfAceAsEleven - DIFFERENCE_OF_ACE_SCORE; + } + + private boolean canCountAceAsOne(int scoreOfAceAsEleven, int aceCount) { + return scoreOfAceAsEleven > BLACKJACK && aceCount > ZERO; + } + + private int getAceCount() { + return (int) cards.stream() + .filter(Card::isAce) + .count(); + } + + private int sumOfCardsScore() { + return cards.stream() + .map(Card::getDenomination) + .mapToInt(Denomination::getScore) + .sum(); + } + + public boolean isBust() { + return getCardsSum() > BLACKJACK; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Participant that = (Participant) o; + return Objects.equals(name, that.name) && Objects.equals(cards, that.cards); + } + + @Override + public int hashCode() { + return Objects.hash(name, cards); + } +}
Java
์ด ๋ถ€๋ถ„ ์ดํ•ด๊ฐ€ ์ž˜ ์•ˆ ๋˜๋Š”๋ฐ์š”, ์ œ ์ƒ๊ฐ์—๋Š” Participant๊ฐ€ ๊ฐ€์ง„ ์นด๋“œ ๋ชฉ๋ก์— ๋”ฐ๋ผ ์—์ด์Šค๋ฅผ 1๋กœ ๊ณ„์‚ฐํ•  ์ง€, 11๋กœ ๊ณ„์‚ฐํ•  ์ง€ ๋‹ค๋ฅด๊ฒŒ ํŒ๋‹จํ•ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— Participant์˜ ๋กœ์ง์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. Denomination ์™ธ๋ถ€์˜ ์กฐ๊ฑด์— ๋”ฐ๋ผ 1 ํ˜น์€ 11๋กœ ๊ณ„์‚ฐ๋˜๊ธฐ ๋•Œ๋ฌธ์— Denomination์„ ํฌํ•จํ•œ ์ƒ์œ„ ๊ตฌ์กฐ์—์„œ ๊ฒฐ์ •ํ•˜๋Š” ๊ฒŒ ๋งž๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. Denomination์— score๋ฅผ 1๋กœ ๊ฐ€์ง€๋Š” enum์„ ์ถ”๊ฐ€ํ•ด์„œ ๋ฆฌํŒฉํ† ๋ง์„ ์‹œ๋„ํ•ด๋ดค๋Š”๋ฐ ์–ด๋–ป๊ฒŒ ํ•ด์•ผ ํ•  ์ง€ ์ž˜ ๋ชจ๋ฅด๊ฒ ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,27 @@ +package blackjack.domain.participant; + +import lombok.Getter; + +@Getter +public class Player extends Participant { + + private static final int PLAYER_DRAW_THRESHOLD = 21; + private static final String DEALER_NAME = "๋”œ๋Ÿฌ"; + private static final String CHECK_SAME_NAME_AS_DEALER = "์ด๋ฆ„์€ ๋”œ๋Ÿฌ์™€ ๊ฐ™์„ ์ˆ˜ ์—†์œผ๋‹ˆ ๋‹ค๋ฅธ ์ด๋ฆ„์„ ์ง€์ •ํ•ด์ฃผ์„ธ์š”."; + + public Player(String name) { + super(name); + validateDealerNameDuplicated(name); + } + + private void validateDealerNameDuplicated(String name) { + if (name.equals(DEALER_NAME)) { + throw new IllegalArgumentException(CHECK_SAME_NAME_AS_DEALER); + } + } + + @Override + public boolean drawable() { + return getCardsSum() < PLAYER_DRAW_THRESHOLD; + } +}
Java
๋ง์”€ํ•˜์‹  ๋ถ€๋ถ„์ด ๋งž๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. ๋ฌธ์ž์—ด ์ƒ์„ฑ ๋กœ์ง์„ view๋กœ ์ด๋™ํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,27 @@ +package blackjack.domain.participant; + +import lombok.Getter; + +@Getter +public class Player extends Participant { + + private static final int PLAYER_DRAW_THRESHOLD = 21; + private static final String DEALER_NAME = "๋”œ๋Ÿฌ"; + private static final String CHECK_SAME_NAME_AS_DEALER = "์ด๋ฆ„์€ ๋”œ๋Ÿฌ์™€ ๊ฐ™์„ ์ˆ˜ ์—†์œผ๋‹ˆ ๋‹ค๋ฅธ ์ด๋ฆ„์„ ์ง€์ •ํ•ด์ฃผ์„ธ์š”."; + + public Player(String name) { + super(name); + validateDealerNameDuplicated(name); + } + + private void validateDealerNameDuplicated(String name) { + if (name.equals(DEALER_NAME)) { + throw new IllegalArgumentException(CHECK_SAME_NAME_AS_DEALER); + } + } + + @Override + public boolean drawable() { + return getCardsSum() < PLAYER_DRAW_THRESHOLD; + } +}
Java
orElseThrow๋กœ ์ˆ˜์ •ํ•˜๊ณ , ๋ฉ”์„ธ์ง€๋ฅผ ๋‹ด์€ ์˜ˆ์™ธ๋ฅผ ๋˜์ง€๋„๋ก ํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -1,16 +1,28 @@ package webserver; -import java.io.DataOutputStream; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import webserver.controller.*; +import webserver.domain.HttpRequest; +import webserver.domain.HttpResponse; + import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import java.util.HashMap; +import java.util.Map; public class RequestHandler implements Runnable { private static final Logger logger = LoggerFactory.getLogger(RequestHandler.class); + private static final Map<String, Controller> controllers = new HashMap<>(); + + static { + controllers.put("/user/create", new CreateUserController()); + controllers.put("/user/login", new LoginController()); + controllers.put("/user/list", new ListUserController()); + controllers.put("/user/list.html", new ListUserController()); + } private Socket connection; @@ -21,35 +33,12 @@ public RequestHandler(Socket connectionSocket) { public void run() { logger.debug("New Client Connect! Connected IP : {}, Port : {}", connection.getInetAddress(), connection.getPort()); - try (InputStream in = connection.getInputStream(); OutputStream out = connection.getOutputStream()) { - // TODO ์‚ฌ์šฉ์ž ์š”์ฒญ์— ๋Œ€ํ•œ ์ฒ˜๋ฆฌ๋Š” ์ด ๊ณณ์— ๊ตฌํ˜„ํ•˜๋ฉด ๋œ๋‹ค. - DataOutputStream dos = new DataOutputStream(out); - byte[] body = "Hello World".getBytes(); - response200Header(dos, body.length); - responseBody(dos, body); - } catch (IOException e) { - logger.error(e.getMessage()); - } - } - - private void response200Header(DataOutputStream dos, int lengthOfBodyContent) { - try { - dos.writeBytes("HTTP/1.1 200 OK \r\n"); - dos.writeBytes("Content-Type: text/html;charset=utf-8\r\n"); - dos.writeBytes("Content-Length: " + lengthOfBodyContent + "\r\n"); - dos.writeBytes("\r\n"); - } catch (IOException e) { - logger.error(e.getMessage()); - } - } - - private void responseBody(DataOutputStream dos, byte[] body) { - try { - dos.write(body, 0, body.length); - dos.flush(); + HttpRequest httpRequest = new HttpRequest(in); + HttpResponse httpResponse = new HttpResponse(out); + controllers.getOrDefault(httpRequest.getPath(), new DefaultController()).service(httpRequest, httpResponse); } catch (IOException e) { logger.error(e.getMessage()); } } -} +} \ No newline at end of file
Java
path์— ๋งž๋Š” Controller ์ •์˜ ์ข‹์Šต๋‹ˆ๋‹ค ๐Ÿ‘
@@ -0,0 +1,80 @@ +package webserver.controller; + +import webserver.domain.HttpRequest; +import webserver.domain.HttpResponse; +import webserver.domain.HttpStatusCode; +import webserver.exceptions.InvalidRequestException; +import webserver.exceptions.NotYetSentException; + +public abstract class AbstractController implements Controller { + + public void service(HttpRequest request, HttpResponse response) { + try { + System.out.println(request.getMethod().name() + " " + request.getPath()); + methodMapping(request, response); + } catch (Exception e) { + if(!response.isSent()){ + System.out.println("์ž์‹ ์ปจํŠธ๋กค๋Ÿฌ์—์„œ ์ฒ˜๋ฆฌ ๋ˆ„๋ฝ๋œ ์˜ˆ์™ธ ์ƒํ™ฉ : " + e.getMessage()); + e.printStackTrace(); + response.send(HttpStatusCode.NOT_IMPLEMENTED, e.getMessage()); + } + } finally { + if (!response.isSent()) { + response.send(HttpStatusCode.INTERNAL_SERVER_ERROR); + throw new NotYetSentException("response์˜ ๋ฉ”์„œ๋“œ send()๊ฐ€ ํ˜ธ์ถœ๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค"); + } + } + } + + private void methodMapping(HttpRequest request, HttpResponse response) { + switch (request.getMethod()) { + case GET: + validateGetRequest(request, response); + doGet(request, response); + return; + case POST: + validatePostRequest(request, response); + doPost(request, response); + return; + case PUT: + validatePutRequest(request, response); + doPut(request, response); + return; + case DELETE: + validateDeleteRequest(request, response); + doDelete(request, response); + return; + default: + response.send(HttpStatusCode.METHOD_NOT_ALLOWED); + } + } + + public void doPost(HttpRequest request, HttpResponse response) { + response.send(HttpStatusCode.METHOD_NOT_ALLOWED); + } + + public void doGet(HttpRequest request, HttpResponse response) { + response.send(HttpStatusCode.METHOD_NOT_ALLOWED); + } + + public void doPut(HttpRequest request, HttpResponse response) { + response.send(HttpStatusCode.METHOD_NOT_ALLOWED); + } + + public void doDelete(HttpRequest request, HttpResponse response) { + response.send(HttpStatusCode.METHOD_NOT_ALLOWED); + } + + // ํ•„์š”์‹œ์— ์˜ค๋ฒ„๋ผ์ด๋”ฉ ํ•˜์—ฌ ์ธํ’‹๊ฐ’์„ ๊ฒ€์ฆํ•œ๋‹ค + public void validatePostRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException { + } + + public void validateGetRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException { + } + + public void validatePutRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException { + } + + public void validateDeleteRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException { + } +}
Java
์ถ”์ƒ ํด๋ž˜์Šค service ๋ฉ”์†Œ๋“œ์— ํ๋ฆ„์„ ์ •๋ฆฌํ•˜์—ฌ ํ…œํ”Œ๋ฆฟ ๋ฉ”์†Œ๋“œ ํŒจํ„ด์œผ๋กœ ์ ์šฉํ•ด์ฃผ์…จ๋„ค์š” ๐Ÿ‘ ๐Ÿ’ฏ
@@ -0,0 +1,21 @@ +package webserver.controller; + +import utils.FileIoUtils; +import webserver.domain.HttpRequest; +import webserver.domain.HttpResponse; +import webserver.domain.HttpStatusCode; + +import java.io.IOException; +import java.net.URISyntaxException; + +public class DefaultController extends AbstractController { + @Override + public void doGet(HttpRequest httpRequest, HttpResponse httpResponse) { + try { + httpResponse.send(HttpStatusCode.OK, FileIoUtils.readStaticHttpFile(httpRequest.getPath())); + } catch (URISyntaxException | IOException e) { + httpResponse.send(HttpStatusCode.NOT_FOUND); + } + } + +}
Java
http://localhost:8080/index.html ๋กœ ์ ‘์†ํ–ˆ์„ ๋•Œ ์ •์ƒ์ ์ธ ํŽ˜์ด์ง€ ํ˜ธ์ถœ์ด ๋˜์ง€ ์•Š๊ณ  ์žˆ์–ด์š”. (index ๋ฟ๋งŒ ์•„๋‹ˆ๋ผ ์ „์ฒด์ ์œผ๋กœ ์›นํŽ˜์ด์ง€ ์‘๋‹ต์ด ์ž˜๋ชป ๋œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!) ์ด ๋ถ€๋ถ„ ํ™•์ธ ๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ํ•ด๋‹น ๋ฉ”์„œ๋“œ๋Š” Controller์˜ ๊ด€์‹ฌ์‚ฌ๊ฐ€ ์•„๋‹Œ๊ฒƒ ๊ฐ™์•„์š”! ์œ ํ‹ธ์„ฑ ํด๋ž˜์Šค๋กœ ๋งŒ๋“ค์–ด์ง€๋Š” ๊ฒƒ์ด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,32 @@ +package webserver.controller; + +import webserver.domain.HttpHeader; +import webserver.domain.HttpRequest; +import webserver.domain.HttpResponse; +import webserver.domain.HttpStatusCode; +import webserver.exceptions.InvalidRequestException; + +import java.io.IOException; + +import static service.JwpService.getProfilePage; +import static service.JwpService.isLogin; + +public class ListUserController extends AbstractController { + @Override + public void doGet(HttpRequest httpRequest, HttpResponse httpResponse) { + try { + httpResponse.send(HttpStatusCode.OK, getProfilePage()); + } catch (IOException e) { + httpResponse.send(HttpStatusCode.INTERNAL_SERVER_ERROR, "์ฝ์–ด๋“ค์ด๋Š”๋ฐ ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€์Šต๋‹ˆ๋‹ค"); + } + } + + @Override + public void validateGetRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException { + if (!isLogin(request.getHeaders().get(HttpHeader.COOKIE))) { + response.getHeaders().add(HttpHeader.LOCATION, "/user/login.html"); + response.send(HttpStatusCode.FOUND); + throw new InvalidRequestException("์ž˜๋ชป๋œ ๋กœ๊ทธ์ธ ์š”์ฒญ"); + } + } +}
Java
TemplateView๋ฅผ ๋งŒ๋“œ๋Š” ๋ถ€๋ถ„๋„ Controller ๋ณด๋‹ค๋Š” ๋‹ค๋ฅธ ๊ณณ์—์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋„๋ก ์œ ํ‹ธ์„ฑ ํด๋ž˜์Šค๋กœ ๋ถ„๋ฆฌํ•˜๋Š”๊ฒŒ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,32 @@ +package webserver.controller; + +import webserver.domain.HttpHeader; +import webserver.domain.HttpRequest; +import webserver.domain.HttpResponse; +import webserver.domain.HttpStatusCode; +import webserver.exceptions.InvalidRequestException; + +import java.io.IOException; + +import static service.JwpService.getProfilePage; +import static service.JwpService.isLogin; + +public class ListUserController extends AbstractController { + @Override + public void doGet(HttpRequest httpRequest, HttpResponse httpResponse) { + try { + httpResponse.send(HttpStatusCode.OK, getProfilePage()); + } catch (IOException e) { + httpResponse.send(HttpStatusCode.INTERNAL_SERVER_ERROR, "์ฝ์–ด๋“ค์ด๋Š”๋ฐ ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€์Šต๋‹ˆ๋‹ค"); + } + } + + @Override + public void validateGetRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException { + if (!isLogin(request.getHeaders().get(HttpHeader.COOKIE))) { + response.getHeaders().add(HttpHeader.LOCATION, "/user/login.html"); + response.send(HttpStatusCode.FOUND); + throw new InvalidRequestException("์ž˜๋ชป๋œ ๋กœ๊ทธ์ธ ์š”์ฒญ"); + } + } +}
Java
login ์ƒํƒœ์ธ์ง€ ์—ฌ๋ถ€๋ฅผ Request๊ฐ€ ์•Œ ์ˆ˜ ์žˆ์ง€ ์•Š์„๊นŒ์š”? ํ•ด๋‹น ํ–‰๋™์„ Request์—๊ฒŒ ์œ„์ž„ํ•ด์ค์‹œ๋‹ค!
@@ -0,0 +1,46 @@ +package webserver.controller; + +import db.DataBase; +import model.User; +import webserver.domain.*; +import webserver.exceptions.InvalidRequestException; + +public class LoginController extends AbstractController { + private static final String INVALID_REQUEST_MESSAGE = "userId, password๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค"; + @Override + public void doPost(HttpRequest httpRequest, HttpResponse httpResponse) { + User findUser = DataBase.findUserById(httpRequest.getParameters().get("userId")); + if(findUser == null){ + sendLoginFailed(httpResponse); + return; + } + if (!findUser.getPassword().equals(httpRequest.getParameters().get("password"))) { + sendLoginFailed(httpResponse); + return; + } + sendLoginSucceeded(httpResponse); + } + + @Override + public void validatePostRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException { + HttpParameters httpParameters = request.getParameters(); + if (httpParameters.contain("userId") && httpParameters.contain("password")) { + return; + } + response.send(HttpStatusCode.BAD_REQUEST, INVALID_REQUEST_MESSAGE); + throw new InvalidRequestException(INVALID_REQUEST_MESSAGE); + } + + private void sendLoginSucceeded(HttpResponse httpResponse) { + httpResponse.getHeaders().add(HttpHeader.SET_COOKIE, "logined=true; Path=/"); + httpResponse.getHeaders().add(HttpHeader.LOCATION, "/index.html"); + httpResponse.send(HttpStatusCode.FOUND); + } + + private void sendLoginFailed(HttpResponse httpResponse) { + httpResponse.getHeaders().add(HttpHeader.SET_COOKIE, "logined=false; Path=/"); + httpResponse.getHeaders().add(HttpHeader.LOCATION, "/user/login_failed.html"); + httpResponse.send(HttpStatusCode.FOUND); + } + +}
Java
response header์— cookie, location ์…‹ํŒ…ํ•ด์ฃผ๋Š” ๋ถ€๋ถ„์€ Response๋กœ ์ฑ…์ž„์„ ์ด๋™์‹œํ‚ฌ ์ˆ˜ ์žˆ์ง€ ์•Š์„๊นŒ์š”? Controller์—์„œ ๋กœ๊ทธ์ธ์—ฌ๋ถ€์™€ location๋งŒ httpResponse์—๊ฒŒ ๋„˜๊ธฐ๋ฉด ์•Œ์•„์„œ ์…‹ํŒ… ๋˜์–ด์•ผํ•  ๊ฒƒ ๊ฐ™์•„์š” :)
@@ -0,0 +1,80 @@ +package webserver.domain; + +import utils.IOUtils; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + + +public class HttpRequest { + private final HttpHeaders headers; + private final HttpParameters parameters; + private HttpMethod method; + private String body; + private String path; + + public HttpRequest(InputStream in) throws IOException { + headers = new HttpHeaders(); + parameters = new HttpParameters(); + BufferedReader reader = new BufferedReader(new InputStreamReader(in)); + + readFirstLine(reader); + readHeaders(reader); + if (headers.contain(HttpHeader.CONTENT_LENGTH)) { + body = IOUtils.readData(reader, Integer.parseInt(headers.get(HttpHeader.CONTENT_LENGTH))); + parameters.parseAndSet(body); + } + } + + private void readFirstLine(BufferedReader reader) throws IOException { + String[] firstLineTokens = reader.readLine().split(" "); + String requestUrl = firstLineTokens[1]; + method = HttpMethod.valueOf(firstLineTokens[0]); + parseUrl(requestUrl); + } + + private void readHeaders(BufferedReader reader) throws IOException { + String line = reader.readLine(); + while (isValid(line)) { + String[] header = line.split(": "); + headers.add(header[0], header[1]); + line = reader.readLine(); + } + } + + private boolean isValid(String line) { + return (line != null) && !"".equals(line); + } + + private void parseUrl(String requestUrl) { + if (requestUrl.indexOf('?') == -1) { + path = requestUrl; + return; + } + String[] urlToken = requestUrl.split("\\?"); + path = urlToken[0]; + parameters.parseAndSet(urlToken[1]); + } + + public HttpHeaders getHeaders() { + return headers; + } + + public HttpParameters getParameters() { + return parameters; + } + + public HttpMethod getMethod() { + return method; + } + + public String getBody() { + return body; + } + + public String getPath() { + return path; + } +}
Java
Request-Line์„ ํŒŒ์‹ฑํ•  ๋•Œ 1, 0 ๊ณผ ๊ฐ™์€ ์˜๋ฏธ๋ฅผ ์ฐพ๊ธฐ ์–ด๋ ค์šด ๋กœ์ง์ด ์กด์žฌํ•˜๋Š”๋ฐ์š”! firstLine์€ ์ŠคํŽ™์ƒ Method SP Request-URI SP HTTP-Version CRLF ์œผ๋กœ ์ •์˜๋ฉ๋‹ˆ๋‹ค. ์ŠคํŽ™์„ ๋งค์น˜ ํŒจํ„ด์œผ๋กœ ์ •์˜ํ•˜๊ณ  ๊ทธ์— ๋งž๊ฒŒ Index ์˜๋ฏธ๋ฅผ ๋ถ€์—ฌํ•ด์ฃผ๋Š”๊ฑด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,21 @@ +package webserver.controller; + +import utils.FileIoUtils; +import webserver.domain.HttpRequest; +import webserver.domain.HttpResponse; +import webserver.domain.HttpStatusCode; + +import java.io.IOException; +import java.net.URISyntaxException; + +public class DefaultController extends AbstractController { + @Override + public void doGet(HttpRequest httpRequest, HttpResponse httpResponse) { + try { + httpResponse.send(HttpStatusCode.OK, FileIoUtils.readStaticHttpFile(httpRequest.getPath())); + } catch (URISyntaxException | IOException e) { + httpResponse.send(HttpStatusCode.NOT_FOUND); + } + } + +}
Java
์›นํŽ˜์ด์ง€๊ฐ€ ์ž˜ ๋œจ๋Š”๊ฒŒ ์•„๋‹ˆ๋ผ์„œ ์†Œ์Šค๋Š” ์ž˜ ๋ฐ›์•„์˜ค๋Š”๋ฐ ์™œ ๊ทธ๋žฌ๋‚˜ ์‹ถ์—ˆ๋Š”๋ฐ, ๋ฒ„๊ทธ์˜€๋„ค์š”. ์ž˜ ๊ณ ์ณ์„œ ๋ฐ˜์˜ํ• ๊ฒŒ์š”!
@@ -0,0 +1,80 @@ +package webserver.domain; + +import utils.IOUtils; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + + +public class HttpRequest { + private final HttpHeaders headers; + private final HttpParameters parameters; + private HttpMethod method; + private String body; + private String path; + + public HttpRequest(InputStream in) throws IOException { + headers = new HttpHeaders(); + parameters = new HttpParameters(); + BufferedReader reader = new BufferedReader(new InputStreamReader(in)); + + readFirstLine(reader); + readHeaders(reader); + if (headers.contain(HttpHeader.CONTENT_LENGTH)) { + body = IOUtils.readData(reader, Integer.parseInt(headers.get(HttpHeader.CONTENT_LENGTH))); + parameters.parseAndSet(body); + } + } + + private void readFirstLine(BufferedReader reader) throws IOException { + String[] firstLineTokens = reader.readLine().split(" "); + String requestUrl = firstLineTokens[1]; + method = HttpMethod.valueOf(firstLineTokens[0]); + parseUrl(requestUrl); + } + + private void readHeaders(BufferedReader reader) throws IOException { + String line = reader.readLine(); + while (isValid(line)) { + String[] header = line.split(": "); + headers.add(header[0], header[1]); + line = reader.readLine(); + } + } + + private boolean isValid(String line) { + return (line != null) && !"".equals(line); + } + + private void parseUrl(String requestUrl) { + if (requestUrl.indexOf('?') == -1) { + path = requestUrl; + return; + } + String[] urlToken = requestUrl.split("\\?"); + path = urlToken[0]; + parameters.parseAndSet(urlToken[1]); + } + + public HttpHeaders getHeaders() { + return headers; + } + + public HttpParameters getParameters() { + return parameters; + } + + public HttpMethod getMethod() { + return method; + } + + public String getBody() { + return body; + } + + public String getPath() { + return path; + } +}
Java
๋งค์น˜ ํŒจํ„ด ์ข‹๋„ค์š” ์•„์ง ๋ฐ˜์˜์„ ๋ชปํ•˜์˜€์ง€๋งŒ ๋งค์น˜ ํŒจํ„ด์ด๋ผ๋Š” ์•„์ด๋””์–ด ์•Œ๋ ค์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,46 @@ +package webserver.controller; + +import db.DataBase; +import model.User; +import webserver.domain.*; +import webserver.exceptions.InvalidRequestException; + +public class LoginController extends AbstractController { + private static final String INVALID_REQUEST_MESSAGE = "userId, password๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค"; + @Override + public void doPost(HttpRequest httpRequest, HttpResponse httpResponse) { + User findUser = DataBase.findUserById(httpRequest.getParameters().get("userId")); + if(findUser == null){ + sendLoginFailed(httpResponse); + return; + } + if (!findUser.getPassword().equals(httpRequest.getParameters().get("password"))) { + sendLoginFailed(httpResponse); + return; + } + sendLoginSucceeded(httpResponse); + } + + @Override + public void validatePostRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException { + HttpParameters httpParameters = request.getParameters(); + if (httpParameters.contain("userId") && httpParameters.contain("password")) { + return; + } + response.send(HttpStatusCode.BAD_REQUEST, INVALID_REQUEST_MESSAGE); + throw new InvalidRequestException(INVALID_REQUEST_MESSAGE); + } + + private void sendLoginSucceeded(HttpResponse httpResponse) { + httpResponse.getHeaders().add(HttpHeader.SET_COOKIE, "logined=true; Path=/"); + httpResponse.getHeaders().add(HttpHeader.LOCATION, "/index.html"); + httpResponse.send(HttpStatusCode.FOUND); + } + + private void sendLoginFailed(HttpResponse httpResponse) { + httpResponse.getHeaders().add(HttpHeader.SET_COOKIE, "logined=false; Path=/"); + httpResponse.getHeaders().add(HttpHeader.LOCATION, "/user/login_failed.html"); + httpResponse.send(HttpStatusCode.FOUND); + } + +}
Java
Response์— ๋„˜๊ฒจ์ฃผ๋ ค๊ณ  ํ•˜์˜€์ง€๋งŒ Response๊ฐ€ ์ˆœ์ˆ˜ํ•˜๊ฒŒ HTTP ์ŠคํŽ™์— ๋”ฐ๋ฅธ ์ „์†ก๋งŒ ๋˜๋„๋ก ๊ฐ„๊ฒฐํ•˜๊ฒŒ ์งœ์—ฌ์ ธ์žˆ์–ด์„œ ์ค‘๊ฐ„ ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“œ๋Š” ๋ฐฉ๋ฒ•์œผ๋กœ ๊ณ ๋ฏผํ•ด๋ณด๊ณ  ์žˆ์–ด์š”.
@@ -0,0 +1,32 @@ +package webserver.controller; + +import webserver.domain.HttpHeader; +import webserver.domain.HttpRequest; +import webserver.domain.HttpResponse; +import webserver.domain.HttpStatusCode; +import webserver.exceptions.InvalidRequestException; + +import java.io.IOException; + +import static service.JwpService.getProfilePage; +import static service.JwpService.isLogin; + +public class ListUserController extends AbstractController { + @Override + public void doGet(HttpRequest httpRequest, HttpResponse httpResponse) { + try { + httpResponse.send(HttpStatusCode.OK, getProfilePage()); + } catch (IOException e) { + httpResponse.send(HttpStatusCode.INTERNAL_SERVER_ERROR, "์ฝ์–ด๋“ค์ด๋Š”๋ฐ ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€์Šต๋‹ˆ๋‹ค"); + } + } + + @Override + public void validateGetRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException { + if (!isLogin(request.getHeaders().get(HttpHeader.COOKIE))) { + response.getHeaders().add(HttpHeader.LOCATION, "/user/login.html"); + response.send(HttpStatusCode.FOUND); + throw new InvalidRequestException("์ž˜๋ชป๋œ ๋กœ๊ทธ์ธ ์š”์ฒญ"); + } + } +}
Java
Request ์— ์œ„์ž„ํ•˜๋ฉด ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ๋งคํ•‘ํ•˜๊ณ , ๊ฐ’์„ ํ• ๋‹นํ•˜๋Š” Request ์—ญํ• ๊นŒ์ง€๋งŒ ๋งก๊ธด ์ƒํƒœ๋ผ ์ค‘๊ฐ„ ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“œ๋Š” ๋ฐฉ์‹์œผ๋กœ ๊ณ ๋ฏผ์„ ํ•ด๋ณด์•˜์–ด์š”. ๊ทธ๋Ÿฌ๋‹ค๊ฐ€, Spring ์— ์žˆ๋Š” ArgumentResolver ์™€ ์œ ์‚ฌํ•˜๊ฒŒ, ๊ฒ€์ฆ์ด ํ•„์š”ํ•œ ๋•Œ์—๋งŒ ์˜ค๋ฒ„๋ผ์ด๋”ฉ ํ•˜๋„๋ก AbstractController์— validate...Request ๋ผ๋Š” ๋ฉ”์„œ๋“œ๋“ค์„ ๋งŒ๋“ค์–ด ๋ณด์•˜์Šต๋‹ˆ๋‹ค. ์ด ๊ฒฝ์šฐ, ๋กœ๊ทธ์ธ์ด ํ•„์š”ํ•œ ์œ ์‚ฌํ•œ ์ปจํŠธ๋กค๋Ÿฌ์— ๋Œ€ํ•ด์„œ ์ค‘๋ณต ์ฝ”๋“œ๊ฐ€ ์ƒ์„ฑ๋œ๋‹ค๋Š” ๋ถ€๋‹ด์ด ์žˆ๋Š”๋ฐ, ๋กœ๊ทธ์ธ ์„œ๋น„์Šค๋ฅผ ํ†ตํ•ฉํ•˜๋Š” ์ถ”์ƒ ๊ฐ์ฒด์ธ ๋กœ๊ทธ์ธ ์ปจํŠธ๋กค๋Ÿฌ๋ฅผ ๋งŒ๋“ค๊ฑฐ๋‚˜, ๋‚˜์ค‘์— MVC ๋ชจ๋ธ์ธ ์–ด๋…ธํ…Œ์ด์…˜์„ ์ ์šฉํ• ๊นŒํ•˜๋Š”๋ฐ ์ด๋Ÿฐ ๋ฐฉ์‹์€ ์–ด๋–ค๊ฐ€์š”?
@@ -0,0 +1,45 @@ +package controller; + +import controller.handler.Handler; +import exception.utils.NoFileException; +import model.request.HttpRequest; +import model.response.HttpResponse; +import model.PathInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; + +public abstract class Controller { + private static final Logger log = LoggerFactory.getLogger( Controller.class ); + protected final Map<PathInfo, Handler> handlers = new HashMap<>(); + protected String basePath = ""; + + public void putHandler(String path, String method, Handler handler) { + handlers.put(new PathInfo(basePath + path, method), handler); + } + + public void setBasePath(String basePath) { + this.basePath = basePath; + } + + public boolean hasSameBasePath(String path) { + return path.startsWith(basePath); + } + + public boolean handle(HttpRequest request, HttpResponse response) throws NoFileException, IOException { + for (Map.Entry<PathInfo, Handler> entry : handlers.entrySet()) { + log.info("matching {} with controller {}", request.getPath(), entry.getKey().getPath()); + + if (request.getPath().matches(entry.getKey().getPath())) { + log.info("handling {} with controller {}", request.getPath(), entry.getKey().getPath()); + entry.getValue().handle(request, response); + return true; + } + } + return false; + } +}
Java
handlers ๋Š” ๊ตณ์ด LinkedHashMap ์„ ์‚ฌ์šฉํ•œ ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,30 @@ +package model; + +import java.util.Objects; + +public class PathInfo { + private final String path; + private final String method; + + public PathInfo(String path, String method) { + this.path = path; + this.method = method; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + PathInfo that = (PathInfo) o; + return Objects.equals(path, that.path) && Objects.equals(method, that.method); + } + + @Override + public int hashCode() { + return Objects.hash(path, method); + } + + public String getPath() { + return path; + } +}
Java
PathInfo ๊ฐ์ฒด๋ฅผ ๋ณ„๋„๋กœ ์„ ์–ธํ•˜์…จ๊ตฐ์š” ๐Ÿ’ฏ
@@ -0,0 +1,44 @@ +package controller; + +import controller.handler.SecuredHandler; +import model.request.HttpRequest; +import model.response.HttpResponse; +import service.UserService; +import view.View; + +import java.io.IOException; +import java.io.OutputStream; + +public class UserController extends Controller { + { + setBasePath("/user"); + putHandler("/create", "POST", this::handleCreate); + putHandler("/login", "POST", this::handleLogin); + putHandler("/list", "GET", new SecuredHandler(this::handleUserList)); + putHandler("/logout", "GET", new SecuredHandler(this::handleLogout)); + } + + private UserService userService = new UserService(); + + public void handleCreate(HttpRequest request, HttpResponse response) { + userService.addUser(request.getParsedBody()); + response.sendRedirect("/index.html"); + } + + public void handleLogin(HttpRequest request, HttpResponse response) { + if (!userService.login(request.getParsedBody())) { + response.setCookie("logined=false").sendRedirect("/user/login_failed.html"); + return; + } + response.setCookie("logined=true").sendRedirect("/index.html"); + } + + public void handleUserList(HttpRequest request, HttpResponse response) throws IOException { + byte[] body = View.getUsersView(userService.findAll(), "/user/list"); + response.sendView(body); + } + + public void handleLogout(HttpRequest request, HttpResponse response) throws IOException { + response.setCookie("logined=false").sendRedirect("/index.html"); + } +}
Java
DataBase ์— ์ง์ ‘ ์ ‘๊ทผํ•˜์ง€ ๋ง๊ณ  ๋ณ„๋„์˜ ์„œ๋น„์Šค ํด๋ž˜์Šค๋กœ ๋ถ„๋ฆฌํ•ด๋ณด๋ฉด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,44 @@ +package controller; + +import controller.handler.SecuredHandler; +import model.request.HttpRequest; +import model.response.HttpResponse; +import service.UserService; +import view.View; + +import java.io.IOException; +import java.io.OutputStream; + +public class UserController extends Controller { + { + setBasePath("/user"); + putHandler("/create", "POST", this::handleCreate); + putHandler("/login", "POST", this::handleLogin); + putHandler("/list", "GET", new SecuredHandler(this::handleUserList)); + putHandler("/logout", "GET", new SecuredHandler(this::handleLogout)); + } + + private UserService userService = new UserService(); + + public void handleCreate(HttpRequest request, HttpResponse response) { + userService.addUser(request.getParsedBody()); + response.sendRedirect("/index.html"); + } + + public void handleLogin(HttpRequest request, HttpResponse response) { + if (!userService.login(request.getParsedBody())) { + response.setCookie("logined=false").sendRedirect("/user/login_failed.html"); + return; + } + response.setCookie("logined=true").sendRedirect("/index.html"); + } + + public void handleUserList(HttpRequest request, HttpResponse response) throws IOException { + byte[] body = View.getUsersView(userService.findAll(), "/user/list"); + response.sendView(body); + } + + public void handleLogout(HttpRequest request, HttpResponse response) throws IOException { + response.setCookie("logined=false").sendRedirect("/index.html"); + } +}
Java
์œ„์™€ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ์ง์ ‘ DataBase ์— ์ ‘๊ทผํ•˜๊ธฐ ๋ณด๋‹ค ์„œ๋น„์Šค ๊ฐ์ฒด๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ์–ด๋–จ๊นŒ์š”? ๋„˜๊ฒจ์ค€ ๊ฐ’์„ ๊ธฐ๋ฐ˜์œผ๋กœ ๋กœ๊ทธ์ธ ๋˜์—ˆ๋Š”์ง€ ๋˜์ง€ ์•Š์•˜๋Š”์ง€ ์—ฌ๋ถ€๋ฅผ boolean ๊ฐ’์œผ๋กœ ์กฐํšŒํ•  ์ˆ˜ ์žˆ๋‹ค๋ฉด ์ข€ ๋” ๊ฐ„๊ฒฐํ•œ ์ฝ”๋“œ๋กœ ๊ฐœ์„ ํ•  ์ˆ˜ ์žˆ์„๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,45 @@ +package controller; + +import controller.handler.Handler; +import exception.utils.NoFileException; +import model.request.HttpRequest; +import model.response.HttpResponse; +import model.PathInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; + +public abstract class Controller { + private static final Logger log = LoggerFactory.getLogger( Controller.class ); + protected final Map<PathInfo, Handler> handlers = new HashMap<>(); + protected String basePath = ""; + + public void putHandler(String path, String method, Handler handler) { + handlers.put(new PathInfo(basePath + path, method), handler); + } + + public void setBasePath(String basePath) { + this.basePath = basePath; + } + + public boolean hasSameBasePath(String path) { + return path.startsWith(basePath); + } + + public boolean handle(HttpRequest request, HttpResponse response) throws NoFileException, IOException { + for (Map.Entry<PathInfo, Handler> entry : handlers.entrySet()) { + log.info("matching {} with controller {}", request.getPath(), entry.getKey().getPath()); + + if (request.getPath().matches(entry.getKey().getPath())) { + log.info("handling {} with controller {}", request.getPath(), entry.getKey().getPath()); + entry.getValue().handle(request, response); + return true; + } + } + return false; + } +}
Java
handle ๋ฉ”์„œ๋“œ์˜ ์ฒซ๋ฒˆ์งธ ์ธ์ž๋Š” HttpRequest ์ธ๋ฐ, ๋‘๋ฒˆ์งธ ์ธ์ž๋Š” OutputStream ์ด๋„ค์š”. HttpRequest / HttpResponse ํ˜•ํƒœ๊ฐ€ ๋” ์ ํ•ฉํ•ด ๋ณด์ž…๋‹ˆ๋‹ค ๐Ÿ˜„
@@ -0,0 +1,66 @@ +package controller; + +import controller.error.ErrorHandlerFactory; +import controller.handler.Handler; +import exception.utils.NoFileException; +import model.request.HttpRequest; +import model.response.HttpResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import webserver.RequestHandler; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.Socket; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +public class ControllerManager { + private static final Logger log = LoggerFactory.getLogger(RequestHandler.class); + private static final List<Controller> controllers = new ArrayList<>(); + static { + registerController(new ViewController()); + registerController(new UserController()); + } + + public static void registerController(Controller controller) { + controllers.add(controller); + } + + public static void runControllers(Socket connection) { + try (InputStream in = connection.getInputStream(); OutputStream out = connection.getOutputStream()) { + HttpRequest httpRequest = HttpRequest.of(in); + HttpResponse httpResponse = HttpResponse.of(out); + handleRequest(httpRequest, httpResponse); + } catch (IOException e) { + log.error("{} {}", e.getMessage(), e.getStackTrace()); + } + } + + private static void handleRequest(HttpRequest httpRequest, HttpResponse httpResponse) { + List<Controller> selectedControllers = controllers.stream() + .filter(controller -> controller.hasSameBasePath(httpRequest.getPath())) + .collect(Collectors.toList()); + try { + for (Controller controller : selectedControllers) { + if (controller.handle(httpRequest, httpResponse)) return; + } + + defaultHandle(httpRequest, httpResponse); + } catch (NoFileException | IOException | RuntimeException e) { + Handler errorHandler = ErrorHandlerFactory.getHandler(e); + try { + errorHandler.handle(httpRequest, httpResponse); + log.warn(e.getMessage()); + } catch (Exception handleError) { + log.error("{} {}", handleError.getMessage(), handleError.getStackTrace()); + } + } + } + + public static void defaultHandle(HttpRequest request, HttpResponse response) throws NoFileException { + response.forward("./templates", request.getPath()); + } +}
Java
์ปจํŠธ๋กค๋Ÿฌ ๋งค๋‹ˆ์ €๊นŒ์ง€ ์ž‘์„ฑํ•˜์…จ๋„ค์š” ๐Ÿ‘
@@ -1,16 +1,48 @@ package model; +import exception.user.WrongEmailException; +import exception.user.WrongIdException; +import exception.user.WrongNameException; +import exception.user.WrongPasswordException; + public class User { - private String userId; - private String password; - private String name; - private String email; + private final String userId; + private final String password; + private final String name; + private final String email; public User(String userId, String password, String name, String email) { - this.userId = userId; - this.password = password; - this.name = name; - this.email = email; + this.userId = validateId(userId); + this.password = validatePw(password); + this.name = validateName(name); + this.email = validateEmail(email.replace("%40", "@")); + } + + private String validatePw(String password) { + if(!password.matches("^[\\w]{1,30}$")){ + throw new WrongPasswordException(); + } + return password; + } + + private String validateId(String userId) { + if(!userId.matches("^[\\w]{1,30}$")) + throw new WrongIdException(); + return userId; + } + + private String validateName(String name) { + if (!name.matches("^[\\w๊ฐ€-ํžฃ]{1,30}$")) { + throw new WrongNameException(); + } + return name; + } + + private String validateEmail(String email) { + if(!email.matches("^[\\w]{1,30}@[\\w]{1,30}.[\\w]{1,30}$")){ + throw new WrongEmailException(); + } + return email; } public String getUserId() {
Java
validation ๋กœ์ง์„ ์ถ”๊ฐ€ํ•˜์‹  ๊ฒƒ์€ ๊ธ์ •์ ์ž…๋‹ˆ๋‹ค. ๋‹ค๋งŒ User ๊ฐ์ฒด๊ฐ€ ์ธ์Šคํ„ด์Šคํ™” ๋  ๋•Œ๋งˆ๋‹ค validate ๋ฉ”์„œ๋“œ๊ฐ€ ํ˜ธ์ถœ๋˜๊ฒŒ ๋˜๋Š”๋ฐ์š”. User ๋ผ๋Š” ๋„๋ฉ”์ธ ๋ชจ๋ธ์ด ๊ฐ–์ถ”๊ณ  ์žˆ์–ด์•ผํ•  ํ•„์ˆ˜์ ์ธ validation ์ธ์ง€ ์•„๋‹ˆ๋ฉด ์ƒˆ๋กœ์šด User ๋ฅผ ์ƒ์„ฑํ•˜๋Š” ์‚ฌ์šฉ์ž์˜ ์š”์ฒญ์—์„œ๋งŒ ํ•„์š”ํ•œ validation ์ธ์ง€์— ๋”ฐ๋ผ์„œ User ๊ฐ์ฒด์—์„œ ์ฒ˜๋ฆฌํ•˜๋Š”๊ฒŒ ์ ํ•ฉํ•  ์ˆ˜๋„ ์žˆ๊ณ  / Controller ์˜์—ญ์—์„œ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ์ด ๋” ๋‚˜์„ ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด๋ถ€๋ถ„์€ ํ•œ๋ฒˆ ๊ณ ๋ฏผํ•ด๋ด์ฃผ์„ธ์š” ๐Ÿ˜„
@@ -0,0 +1,7 @@ +package exception.utils; + +public class NoFileException extends Exception { + public NoFileException(String path) { + super(path + " ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } +}
Java
NoFIleException ๊ณผ ๊ฐ™์€ ๊ฒฝ์šฐ์—๋Š” ์–ด๋–ค ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†๋Š”์ง€ ํ‘œ์‹œ๋  ์ˆ˜ ์žˆ๊ฒŒ ๊ฐœ์„ ๋˜๋ฉด ๋” ์ข‹๊ฒ ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,30 @@ +package controller; + +import exception.utils.NoFileException; +import model.request.HttpRequest; +import model.response.HttpResponse; + +import java.io.IOException; +import java.io.OutputStream; + +public class ViewController extends Controller { + + { + setBasePath(""); + putHandler("/js/.*", "GET", this::handleFile); + putHandler("/css/.*", "GET", this::handleFile); + putHandler("/fonts/.*", "GET", this::handleFile); + putHandler("/favicon.ico", "GET", this::handleFile); + putHandler("/index.html", "GET", this::handleView); + putHandler("/", "GET", this::handleView); + } + + public void handleFile(HttpRequest request, HttpResponse response) throws NoFileException { + response.forward("./static", request.getPath()); + } + + public void handleView(HttpRequest request, HttpResponse response) throws NoFileException { + response.forward("./templates", + (request.getPath().equals("/") ? "/index.html" : request.getPath())); + } +}
Java
![image](https://user-images.githubusercontent.com/1266944/106766656-68cad300-667d-11eb-9e7b-52fffd02632d.png) Fonts ํŒŒ์ผ์ด ๋กœ๋”ฉ๋˜์ง€ ์•Š๋Š” ํ˜„์ƒ์ด ์žˆ์Šต๋‹ˆ๋‹ค. ํ™•์ธ ๋ถ€ํƒ๋“œ๋ ค์š” :smile
@@ -0,0 +1,45 @@ +package controller; + +import controller.handler.Handler; +import exception.utils.NoFileException; +import model.request.HttpRequest; +import model.response.HttpResponse; +import model.PathInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; + +public abstract class Controller { + private static final Logger log = LoggerFactory.getLogger( Controller.class ); + protected final Map<PathInfo, Handler> handlers = new HashMap<>(); + protected String basePath = ""; + + public void putHandler(String path, String method, Handler handler) { + handlers.put(new PathInfo(basePath + path, method), handler); + } + + public void setBasePath(String basePath) { + this.basePath = basePath; + } + + public boolean hasSameBasePath(String path) { + return path.startsWith(basePath); + } + + public boolean handle(HttpRequest request, HttpResponse response) throws NoFileException, IOException { + for (Map.Entry<PathInfo, Handler> entry : handlers.entrySet()) { + log.info("matching {} with controller {}", request.getPath(), entry.getKey().getPath()); + + if (request.getPath().matches(entry.getKey().getPath())) { + log.info("handling {} with controller {}", request.getPath(), entry.getKey().getPath()); + entry.getValue().handle(request, response); + return true; + } + } + return false; + } +}
Java
Handlers ๊ฐ€ ์ˆœ์„œ๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ๋“ฑ๋ก๋˜์–ด์•ผ ํ•  ํ•„์š”๊ฐ€ ์žˆ๋‹ค๋ฉด ์ฐจํ›„์— ์‹ค์ˆ˜ํ•˜๊ธฐ ์‰ฌ์šด ๊ตฌ์กฐ ์ž…๋‹ˆ๋‹ค. path ๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ๋™์ž‘ํ•  handler ๊ฐ€ ๋‹ค๋ฅธ ๋ฐฉ์‹์œผ๋กœ ๋งค์นญ๋  ์ˆ˜๋Š” ์—†์„์ง€ ๊ณ ๋ฏผํ•ด๋ด์ฃผ์„ธ์š” ๐Ÿ˜„
@@ -0,0 +1,85 @@ +package model.request; + +import utils.IOUtils; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +public class HttpRequest { + private HttpRequestLine httpRequestLine; + private HttpRequestHeader httpRequestHeader; + + private String body = ""; + + private HttpRequest(BufferedReader br) throws IOException { + String line = br.readLine(); + httpRequestLine = new HttpRequestLine(line); + httpRequestHeader = new HttpRequestHeader(br); + setBody(br); + } + + public static HttpRequest of(InputStream in) throws IOException { + return new HttpRequest(new BufferedReader(new InputStreamReader(in))); + } + + private void setBody(BufferedReader br) throws IOException { + while(br.ready()){ + body = IOUtils.readData(br, Integer.parseInt(getHeader("Content-Length"))); + } + } + + public String getBody() { + return body; + } + + public Map<String, String> getParsedBody(){ + Map<String, String> parsedBody = new HashMap<>(); + String[] queryParams = body.split("&"); + Arrays.stream(queryParams).forEach((param) -> { + String[] args = param.split("=", 2); + parsedBody.put(args[0].trim(), args[1].trim()); + }); + return parsedBody; + } + + public String getCookie(String cookieParam){ + Map<String, String> parsedCookie = new HashMap<>(); + String cookieHeader = getHeader("Cookie"); + + String[] cookies = cookieHeader.split(";"); + Arrays.stream(cookies).forEach((cookie) -> { + String[] args = cookie.split("=", 2); + parsedCookie.put(args[0].trim(), args[1].trim()); + }); + return parsedCookie.get(cookieParam); + } + + public Map<String, String> getHeaderMap() { + return httpRequestHeader.getHeaderMap(); + } + + public String getHeader(String key){ + return httpRequestHeader.getHeader(key); + } + + public String getMethod() { + return httpRequestLine.getMethod(); + } + + public String getPath() { + return httpRequestLine.getPath(); + } + + public String getProtocol() { + return httpRequestLine.getProtocol(); + } + + public Map<String, String> getQueryParameterMap() { + return httpRequestLine.getQueryParameterMap(); + } +}
Java
InputStream ์„ ๋ฐ›์•„์„œ HttpRequest ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑํ•˜๋Š” static method ๋กœ ๋ณ€๊ฒฝํ•ด๋ณด๋Š”๊ฑด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,109 @@ +package chess.domain.board; + +import chess.domain.command.MoveOptions; +import chess.domain.piece.Color; +import chess.domain.piece.Piece; +import chess.domain.player.Player; +import chess.domain.player.Position; + +import java.util.Collection; + +public class Board { + private final Player white; + private final Player black; + + public Board() { + this.white = new Player(Color.WHITE); + this.black = new Player(Color.BLACK); + } + + public void move(final MoveOptions moveOptions, final boolean isWhiteTurn) { + Player player = currentPlayer(isWhiteTurn); + Player enemy = currentPlayer(!isWhiteTurn); + Position source = moveOptions.getSource(); + Position target = moveOptions.getTarget(); + + validate(player, enemy, source, target); + + enemy.removePieceOn(target); + movePiece(player, source, target); + } + + private Player currentPlayer(final boolean isWhiteTurn) { + if (isWhiteTurn) { + return white; + } + return black; + } + + private void validate(final Player player, final Player enemy, final Position source, final Position target) { + validateSourceOwner(enemy, source); + validateSamePosition(source, target); + validateTarget(player, target); + validateKingMovable(player, enemy, source, target); + } + + private void validateSourceOwner(final Player enemy, final Position source) { + if (enemy.hasPieceOn(source)) { + throw new IllegalArgumentException("์ž์‹ ์˜ ๊ธฐ๋ฌผ๋งŒ ์›€์ง์ผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค."); + } + } + + private void validateSamePosition(final Position source, final Position target) { + if (source.equals(target)) { + throw new IllegalArgumentException("์ถœ๋ฐœ ์œ„์น˜์™€ ๋„์ฐฉ ์œ„์น˜๊ฐ€ ๊ฐ™์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + } + + private void validateTarget(final Player player, final Position target) { + if (player.hasPieceOn(target)) { + throw new IllegalArgumentException("๊ฐ™์€ ์ƒ‰์ƒ์˜ ๊ธฐ๋ฌผ์€ ๊ณต๊ฒฉํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + } + + private void validateKingMovable(final Player player, final Player enemy, final Position source, final Position target) { + if (player.hasKingOn(source) && enemy.canAttack(target)) { + throw new IllegalArgumentException("ํ‚น์€ ์ƒ๋Œ€๋ฐฉ์ด ๊ณต๊ฒฉ ๊ฐ€๋Šฅํ•œ ์œ„์น˜๋กœ ์ด๋™ํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + } + + private void movePiece(final Player player, final Position source, final Position target) { + Collection<Position> paths = player.findPaths(source, target); + validatePathsEmpty(paths); + player.update(source, target); + } + + private void validatePathsEmpty(final Collection<Position> paths) { + boolean isWhiteBlocked = paths.stream() + .anyMatch(white::hasPieceOn); + boolean isBlackBlocked = paths.stream() + .anyMatch(black::hasPieceOn); + + if (isWhiteBlocked || isBlackBlocked) { + throw new IllegalArgumentException("๊ธฐ๋ฌผ์„ ํ†ต๊ณผํ•˜์—ฌ ์ด๋™ํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + } + + public Piece findBy(final Position position) { + if (white.hasPieceOn(position)) { + return white.findPieceBy(position); + } + + return black.findPieceBy(position); + } + + public boolean isEmpty(final Position position) { + return !white.hasPieceOn(position) && !black.hasPieceOn(position); + } + + public Status getStatus() { + double whiteScore = white.sumScores(); + double blackScore = black.sumScores(); + + return new Status(whiteScore, blackScore, white.isKingDead(), black.isKingDead()); + } + + public boolean isEnd() { + return white.isKingDead() || black.isKingDead(); + } +}
Java
์ ์ˆ˜ ๊ณ„์‚ฐ์— ๋Œ€ํ•œ ๋ช…๋ น์–ด(`status`) ์ ์šฉ์ด ์•ˆ๋˜์–ด ์žˆ๋Š” ๊ฒƒ ๊ฐ™์•„์š”! :)
@@ -0,0 +1,58 @@ +package chess.domain.command; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +public enum Command { + + START("start"), + END("end"), + MOVE("move"), + STATUS("status"); + + private static final Map<String, Command> COMMANDS = createCommands(); + + private static Map<String, Command> createCommands() { + Map<String, Command> commands = new HashMap<>(); + + Arrays.stream(values()) + .forEach(command -> commands.put(command.command, command)); + + return commands; + } + + private final String command; + + Command(final String command) { + this.command = command; + } + + public static Command of(final String command) { + Command foundCommand = COMMANDS.get(command); + + if (foundCommand == null) { + throw new IllegalArgumentException("์œ ํšจํ•˜์ง€ ์•Š์€ ๋ช…๋ น์–ด์ž…๋‹ˆ๋‹ค."); + } + + return foundCommand; + } + + public void validateInitialCommand() { + if (isStatus() || isMove()) { + throw new IllegalArgumentException(String.format("%s ๋˜๋Š” %s๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”.", START.command, END.command)); + } + } + + public boolean isEnd() { + return this.equals(END); + } + + public boolean isMove() { + return this.equals(MOVE); + } + + public boolean isStatus() { + return this.equals(STATUS); + } +}
Java
Command๋„ Enum์œผ๋กœ ๊ด€๋ฆฌํ•ด๋ณด๋ฉด ์–ด๋–จ๊นŒ์š”? :)
@@ -0,0 +1,127 @@ +package chess.domain.player; + +import chess.domain.board.File; +import chess.domain.piece.Color; +import chess.domain.piece.Piece; +import chess.domain.piece.PieceFactory; +import chess.domain.piece.PieceResolver; + +import java.util.Collection; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class Player { + + private final Map<Position, Piece> pieces; + private final AttackRange attackRange; + + public Player(final Color color) { + pieces = new HashMap<>(PieceFactory.createPieces(color)); + attackRange = new AttackRange(pieces); + } + + public double sumScores() { + double pawnScores = calculatePawnScores(); + double scoresExceptPawn = calculateScoresExceptPawn(); + + return pawnScores + scoresExceptPawn; + } + + private double calculatePawnScores() { + List<Position> pawnPositions = findPawnPositions(); + Map<File, Integer> pawnCountsOnSameFile = extractPawnCountsOnSameFile(pawnPositions); + + return pawnCountsOnSameFile.values() + .stream() + .mapToDouble(PieceResolver::sumPawnScores) + .sum(); + } + + private List<Position> findPawnPositions() { + return pieces.keySet() + .stream() + .filter(position -> { + Piece piece = pieces.get(position); + return piece.isPawn(); + }) + .collect(Collectors.toList()); + } + + private Map<File, Integer> extractPawnCountsOnSameFile(final List<Position> pawnPositions) { + Map<File, Integer> pawnCountOnSameFile = new EnumMap<>(File.class); + + pawnPositions.stream() + .map(Position::getFile) + .forEach(file -> pawnCountOnSameFile.put(file, pawnCountOnSameFile.getOrDefault(file, 0) + 1)); + + return pawnCountOnSameFile; + } + + private double calculateScoresExceptPawn() { + return pieces.values() + .stream() + .filter(Piece::isNotPawn) + .mapToDouble(PieceResolver::findScoreBy) + .sum(); + } + + public Collection<Position> findPaths(final Position source, final Position target) { + Piece sourcePiece = findPieceBy(source); + + return sourcePiece.findPath(source, target); + } + + public Piece findPieceBy(final Position position) { + if (isEmptyOn(position)) { + throw new IllegalArgumentException("ํ•ด๋‹น ์œ„์น˜์— ๊ธฐ๋ฌผ์ด ์กด์žฌํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค."); + } + + return pieces.get(position); + } + + private boolean isEmptyOn(final Position position) { + return !pieces.containsKey(position); + } + + public void update(final Position source, final Position target) { + Piece sourcePiece = findPieceBy(source); + movePiece(source, target, sourcePiece); + attackRange.update(source, target, sourcePiece); + } + + private void movePiece(final Position source, final Position target, final Piece sourcePiece) { + pieces.put(target, sourcePiece); + pieces.remove(source); + } + + public boolean hasKingOn(final Position position) { + Piece piece = findPieceBy(position); + + return piece.isKing(); + } + + public boolean isKingDead() { + return pieces.values().stream() + .noneMatch(Piece::isKing); + } + + public boolean canAttack(final Position position) { + return attackRange.contains(position); + } + + public void removePieceOn(final Position position) { + if (isEmptyOn(position)) { + return; + } + + attackRange.remove(position, pieces.get(position)); + pieces.remove(position); + } + + public boolean hasPieceOn(final Position position) { + return pieces.containsKey(position); + } +}
Java
์ €๋Š” ๋ถ€์ •์—ฐ์‚ฐ์ž(`!`)๋ฅผ ์›ฌ๋งŒํ•˜๋ฉด ํ”ผํ•˜๋Š”๋ฐ์š” ใ…Žใ…Ž ๊ฐ€๋…์„ฑ์˜ ๋ฌธ์ œ๋„ ์žˆ๊ณ , ์ฝ๋Š” ์‚ฌ๋žŒ์ด ํ•œ๋ฒˆ ๋” ํ•ด์„์„ ํ•ด์•ผํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋ฉ”์„œ๋“œ๋ฅผ ์ œ๊ณตํ•˜๋Š” ์ชฝ์—์„œ ํ•œ๋ฒˆ ๋” ์ถ”์ƒํ™”์‹œํ‚ค๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š” ใ…Žใ…Ž `piece.isNotPawn()`
@@ -0,0 +1,127 @@ +package chess.domain.player; + +import chess.domain.board.File; +import chess.domain.piece.Color; +import chess.domain.piece.Piece; +import chess.domain.piece.PieceFactory; +import chess.domain.piece.PieceResolver; + +import java.util.Collection; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class Player { + + private final Map<Position, Piece> pieces; + private final AttackRange attackRange; + + public Player(final Color color) { + pieces = new HashMap<>(PieceFactory.createPieces(color)); + attackRange = new AttackRange(pieces); + } + + public double sumScores() { + double pawnScores = calculatePawnScores(); + double scoresExceptPawn = calculateScoresExceptPawn(); + + return pawnScores + scoresExceptPawn; + } + + private double calculatePawnScores() { + List<Position> pawnPositions = findPawnPositions(); + Map<File, Integer> pawnCountsOnSameFile = extractPawnCountsOnSameFile(pawnPositions); + + return pawnCountsOnSameFile.values() + .stream() + .mapToDouble(PieceResolver::sumPawnScores) + .sum(); + } + + private List<Position> findPawnPositions() { + return pieces.keySet() + .stream() + .filter(position -> { + Piece piece = pieces.get(position); + return piece.isPawn(); + }) + .collect(Collectors.toList()); + } + + private Map<File, Integer> extractPawnCountsOnSameFile(final List<Position> pawnPositions) { + Map<File, Integer> pawnCountOnSameFile = new EnumMap<>(File.class); + + pawnPositions.stream() + .map(Position::getFile) + .forEach(file -> pawnCountOnSameFile.put(file, pawnCountOnSameFile.getOrDefault(file, 0) + 1)); + + return pawnCountOnSameFile; + } + + private double calculateScoresExceptPawn() { + return pieces.values() + .stream() + .filter(Piece::isNotPawn) + .mapToDouble(PieceResolver::findScoreBy) + .sum(); + } + + public Collection<Position> findPaths(final Position source, final Position target) { + Piece sourcePiece = findPieceBy(source); + + return sourcePiece.findPath(source, target); + } + + public Piece findPieceBy(final Position position) { + if (isEmptyOn(position)) { + throw new IllegalArgumentException("ํ•ด๋‹น ์œ„์น˜์— ๊ธฐ๋ฌผ์ด ์กด์žฌํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค."); + } + + return pieces.get(position); + } + + private boolean isEmptyOn(final Position position) { + return !pieces.containsKey(position); + } + + public void update(final Position source, final Position target) { + Piece sourcePiece = findPieceBy(source); + movePiece(source, target, sourcePiece); + attackRange.update(source, target, sourcePiece); + } + + private void movePiece(final Position source, final Position target, final Piece sourcePiece) { + pieces.put(target, sourcePiece); + pieces.remove(source); + } + + public boolean hasKingOn(final Position position) { + Piece piece = findPieceBy(position); + + return piece.isKing(); + } + + public boolean isKingDead() { + return pieces.values().stream() + .noneMatch(Piece::isKing); + } + + public boolean canAttack(final Position position) { + return attackRange.contains(position); + } + + public void removePieceOn(final Position position) { + if (isEmptyOn(position)) { + return; + } + + attackRange.remove(position, pieces.get(position)); + pieces.remove(position); + } + + public boolean hasPieceOn(final Position position) { + return pieces.containsKey(position); + } +}
Java
์œ„์—๋„ ๋ถ€์ •์—ฐ์‚ฐ์ž ํ”ผ๋“œ๋ฐฑ์„ ๋‚จ๊ฒผ๋Š”๋ฐ์š”, ์—ฌ๊ธฐ๋„ ํ•œ๋ฒˆ๋” ์ถ”์ƒํ™”์‹œํ‚ค๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š” ใ…Žใ…Ž ์ „์ฒด์ ์œผ๋กœ ํ•œ๋ฒˆ ๋” ์ฒดํฌํ•ด๋ด๋„ ์ข‹๊ฒ ๋„ค์š” :)
@@ -0,0 +1,109 @@ +package chess.domain.board; + +import chess.domain.command.MoveOptions; +import chess.domain.piece.Color; +import chess.domain.piece.Piece; +import chess.domain.player.Player; +import chess.domain.player.Position; + +import java.util.Collection; + +public class Board { + private final Player white; + private final Player black; + + public Board() { + this.white = new Player(Color.WHITE); + this.black = new Player(Color.BLACK); + } + + public void move(final MoveOptions moveOptions, final boolean isWhiteTurn) { + Player player = currentPlayer(isWhiteTurn); + Player enemy = currentPlayer(!isWhiteTurn); + Position source = moveOptions.getSource(); + Position target = moveOptions.getTarget(); + + validate(player, enemy, source, target); + + enemy.removePieceOn(target); + movePiece(player, source, target); + } + + private Player currentPlayer(final boolean isWhiteTurn) { + if (isWhiteTurn) { + return white; + } + return black; + } + + private void validate(final Player player, final Player enemy, final Position source, final Position target) { + validateSourceOwner(enemy, source); + validateSamePosition(source, target); + validateTarget(player, target); + validateKingMovable(player, enemy, source, target); + } + + private void validateSourceOwner(final Player enemy, final Position source) { + if (enemy.hasPieceOn(source)) { + throw new IllegalArgumentException("์ž์‹ ์˜ ๊ธฐ๋ฌผ๋งŒ ์›€์ง์ผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค."); + } + } + + private void validateSamePosition(final Position source, final Position target) { + if (source.equals(target)) { + throw new IllegalArgumentException("์ถœ๋ฐœ ์œ„์น˜์™€ ๋„์ฐฉ ์œ„์น˜๊ฐ€ ๊ฐ™์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + } + + private void validateTarget(final Player player, final Position target) { + if (player.hasPieceOn(target)) { + throw new IllegalArgumentException("๊ฐ™์€ ์ƒ‰์ƒ์˜ ๊ธฐ๋ฌผ์€ ๊ณต๊ฒฉํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + } + + private void validateKingMovable(final Player player, final Player enemy, final Position source, final Position target) { + if (player.hasKingOn(source) && enemy.canAttack(target)) { + throw new IllegalArgumentException("ํ‚น์€ ์ƒ๋Œ€๋ฐฉ์ด ๊ณต๊ฒฉ ๊ฐ€๋Šฅํ•œ ์œ„์น˜๋กœ ์ด๋™ํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + } + + private void movePiece(final Player player, final Position source, final Position target) { + Collection<Position> paths = player.findPaths(source, target); + validatePathsEmpty(paths); + player.update(source, target); + } + + private void validatePathsEmpty(final Collection<Position> paths) { + boolean isWhiteBlocked = paths.stream() + .anyMatch(white::hasPieceOn); + boolean isBlackBlocked = paths.stream() + .anyMatch(black::hasPieceOn); + + if (isWhiteBlocked || isBlackBlocked) { + throw new IllegalArgumentException("๊ธฐ๋ฌผ์„ ํ†ต๊ณผํ•˜์—ฌ ์ด๋™ํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + } + + public Piece findBy(final Position position) { + if (white.hasPieceOn(position)) { + return white.findPieceBy(position); + } + + return black.findPieceBy(position); + } + + public boolean isEmpty(final Position position) { + return !white.hasPieceOn(position) && !black.hasPieceOn(position); + } + + public Status getStatus() { + double whiteScore = white.sumScores(); + double blackScore = black.sumScores(); + + return new Status(whiteScore, blackScore, white.isKingDead(), black.isKingDead()); + } + + public boolean isEnd() { + return white.isKingDead() || black.isKingDead(); + } +}
Java
์•—.. ํŽ˜์–ด๋ถ„ repo์—์„œ pullํ•˜๊ณ  ํ‘ธ์‹œ๋ฅผ ์•ˆํ–ˆ์—ˆ๋„ค์š” ์ฃ„์†กํ•ฉ๋‹ˆ๋‹คใ… ใ…  ๋ฐ˜์˜ํ•˜์˜€์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,127 @@ +package chess.domain.player; + +import chess.domain.board.File; +import chess.domain.piece.Color; +import chess.domain.piece.Piece; +import chess.domain.piece.PieceFactory; +import chess.domain.piece.PieceResolver; + +import java.util.Collection; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class Player { + + private final Map<Position, Piece> pieces; + private final AttackRange attackRange; + + public Player(final Color color) { + pieces = new HashMap<>(PieceFactory.createPieces(color)); + attackRange = new AttackRange(pieces); + } + + public double sumScores() { + double pawnScores = calculatePawnScores(); + double scoresExceptPawn = calculateScoresExceptPawn(); + + return pawnScores + scoresExceptPawn; + } + + private double calculatePawnScores() { + List<Position> pawnPositions = findPawnPositions(); + Map<File, Integer> pawnCountsOnSameFile = extractPawnCountsOnSameFile(pawnPositions); + + return pawnCountsOnSameFile.values() + .stream() + .mapToDouble(PieceResolver::sumPawnScores) + .sum(); + } + + private List<Position> findPawnPositions() { + return pieces.keySet() + .stream() + .filter(position -> { + Piece piece = pieces.get(position); + return piece.isPawn(); + }) + .collect(Collectors.toList()); + } + + private Map<File, Integer> extractPawnCountsOnSameFile(final List<Position> pawnPositions) { + Map<File, Integer> pawnCountOnSameFile = new EnumMap<>(File.class); + + pawnPositions.stream() + .map(Position::getFile) + .forEach(file -> pawnCountOnSameFile.put(file, pawnCountOnSameFile.getOrDefault(file, 0) + 1)); + + return pawnCountOnSameFile; + } + + private double calculateScoresExceptPawn() { + return pieces.values() + .stream() + .filter(Piece::isNotPawn) + .mapToDouble(PieceResolver::findScoreBy) + .sum(); + } + + public Collection<Position> findPaths(final Position source, final Position target) { + Piece sourcePiece = findPieceBy(source); + + return sourcePiece.findPath(source, target); + } + + public Piece findPieceBy(final Position position) { + if (isEmptyOn(position)) { + throw new IllegalArgumentException("ํ•ด๋‹น ์œ„์น˜์— ๊ธฐ๋ฌผ์ด ์กด์žฌํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค."); + } + + return pieces.get(position); + } + + private boolean isEmptyOn(final Position position) { + return !pieces.containsKey(position); + } + + public void update(final Position source, final Position target) { + Piece sourcePiece = findPieceBy(source); + movePiece(source, target, sourcePiece); + attackRange.update(source, target, sourcePiece); + } + + private void movePiece(final Position source, final Position target, final Piece sourcePiece) { + pieces.put(target, sourcePiece); + pieces.remove(source); + } + + public boolean hasKingOn(final Position position) { + Piece piece = findPieceBy(position); + + return piece.isKing(); + } + + public boolean isKingDead() { + return pieces.values().stream() + .noneMatch(Piece::isKing); + } + + public boolean canAttack(final Position position) { + return attackRange.contains(position); + } + + public void removePieceOn(final Position position) { + if (isEmptyOn(position)) { + return; + } + + attackRange.remove(position, pieces.get(position)); + pieces.remove(position); + } + + public boolean hasPieceOn(final Position position) { + return pieces.containsKey(position); + } +}
Java
๋„ต๋„ต! ํ•ด๋‹น ํ”ผ๋“œ๋ฐฑ ์ฝ์€ ํ›„ ๋ถ€์ •์—ฐ์‚ฐ์ž ์‚ฌ์šฉํ•˜๋Š” ๊ณณ ๋ชจ๋‘ ์ˆ˜์ •ํ•ด์ฃผ์—ˆ์Šต๋‹ˆ๋‹ค :)
@@ -0,0 +1,58 @@ +package chess.domain.command; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +public enum Command { + + START("start"), + END("end"), + MOVE("move"), + STATUS("status"); + + private static final Map<String, Command> COMMANDS = createCommands(); + + private static Map<String, Command> createCommands() { + Map<String, Command> commands = new HashMap<>(); + + Arrays.stream(values()) + .forEach(command -> commands.put(command.command, command)); + + return commands; + } + + private final String command; + + Command(final String command) { + this.command = command; + } + + public static Command of(final String command) { + Command foundCommand = COMMANDS.get(command); + + if (foundCommand == null) { + throw new IllegalArgumentException("์œ ํšจํ•˜์ง€ ์•Š์€ ๋ช…๋ น์–ด์ž…๋‹ˆ๋‹ค."); + } + + return foundCommand; + } + + public void validateInitialCommand() { + if (isStatus() || isMove()) { + throw new IllegalArgumentException(String.format("%s ๋˜๋Š” %s๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”.", START.command, END.command)); + } + } + + public boolean isEnd() { + return this.equals(END); + } + + public boolean isMove() { + return this.equals(MOVE); + } + + public boolean isStatus() { + return this.equals(STATUS); + } +}
Java
์ƒ์ˆ˜๋“ค์ด๊ธฐ ๋•Œ๋ฌธ์— Enum์œผ๋กœ ๊ด€๋ฆฌํ•˜๋Š” ํŽธ์ด ๋” ์ข‹๊ฒ ๋„ค์š”! Enum ๊ฐ์ฒด๋กœ ์ˆ˜์ •ํ•˜์˜€์Šต๋‹ˆ๋‹ค :)
@@ -0,0 +1,12 @@ +.header { + display: flex; + justify-content: space-between; + align-items: center; + position: fixed; + width: calc(430px - 48px); + height: 64px; + padding: 0 24px; + background-color: black; + color: #fff; + z-index: 1000; +}
Unknown
ํ”ผ๊ทธ๋งˆ ์‹œ์•ˆ width๊ฐ€ 430px์ด์—ˆ๊ณ , ์–‘ ์˜† padding์ด 24์˜€์–ด์„œ ์ด๋Ÿฐ calc ์ฝ”๋“œ๊ฐ€ ๋‚˜์™”์Šต๋‹ˆ๋‹ค.. โœ‹๐Ÿป๋ณดํ†ต ์ด๋ ‡๊ฒŒ ์ฒ˜๋ฆฌํ•˜์‹œ๋Š”์ง€, ํ˜น์€ ๋” ์œ ์—ฐํ•œ ๋ฐฉ์‹์ด ์žˆ๋Š”์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค.
@@ -4,13 +4,15 @@ "version": "0.0.0", "type": "module", "scripts": { - "dev": "vite", + "dev": "vite --host", "build": "tsc && vite build", "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0", "preview": "vite preview", "test": "vitest" }, "dependencies": { + "@jaymyong66/simple-modal": "^0.0.7", + "@tanstack/react-query": "^5.40.1", "react": "^18.2.0", "react-dom": "^18.2.0" },
Unknown
๊ต‰์žฅํžˆ ์‚ฌ์†Œํ•˜์ง€๋งŒ ์ปค๋ฐ‹ ๋ฉ”์‹œ์ง€ ๊ด€๋ จ ๋ฆฌ๋ทฐ ๋‚จ๊ฒจ๋ด…๋‹ˆ๋‹ค..! ์ €๋Š” ํŒจํ‚ค์ง€ ๊ด€๋ จ ์„ค์น˜๋Š” chore๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค..! ์ด๊ฒŒ ์™„๋ฒฝํ•˜๊ฒŒ ์ •ํ™•ํ•œ ์ง€๋Š” ๊ฒ€์ฆํ•ด๋ณด์ง€ ์•Š์•˜์œผ๋‚˜, ์ฐธ๊ณ ํ•ด๋ณด๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”! [์ข‹์€ ์ปค๋ฐ‹ ๋ฉ”์‹œ์ง€ ์ž‘์„ฑ๋ฒ•](https://velog.io/@iamjm29/Git-%EC%A2%8B%EC%9D%80-%EC%BB%A4%EB%B0%8B-%EB%A9%94%EC%8B%9C%EC%A7%80-%EC%9E%91%EC%84%B1%EB%B2%95) [AngularJS Commit Convention](https://gist.github.com/stephenparish/9941e89d80e2bc58a153)
@@ -0,0 +1,12 @@ +.header { + display: flex; + justify-content: space-between; + align-items: center; + position: fixed; + width: calc(430px - 48px); + height: 64px; + padding: 0 24px; + background-color: black; + color: #fff; + z-index: 1000; +}
Unknown
๋Œ€๋ฐ• ์™œ ์ด์ œ ์•Œ์•˜์ง€..? ๐Ÿ‘
@@ -0,0 +1,46 @@ +package lottodomain; + +import java.util.ArrayList; +import java.util.List; + +public class LottoGame { + private static final int PRICE_PER_LOTTO = 1000; + + private List<Lotto> allLotto; + private int numberOfAllLotto; + + public LottoGame(int inputMoney, List<List<Integer>> manualLottoNos) { + numberOfAllLotto = inputMoney / PRICE_PER_LOTTO; + allLotto = issueLottos(manualLottoNos); + } + + public LottoAnalyzer getLottoAnalyzer(WinningNos winningNos) { + return new LottoAnalyzer(allLotto, winningNos); + } + + public List<Lotto> getAllLotto() { + return allLotto; + } + + private List<Lotto> issueLottos(List<List<Integer>> manualLottoNos) { + List<Lotto> lottos = issueManualLottos(manualLottoNos); + lottos.addAll(issueAutoLottos(numberOfAllLotto - lottos.size())); + return lottos; + } + + private List<Lotto> issueManualLottos(List<List<Integer>> manualLottoNos) { + List<Lotto> ManualLottos = new ArrayList<>(); + for (int i = 0; i < manualLottoNos.size(); i++) { + ManualLottos.add(LottoGenerator.generateLottoWithNos(manualLottoNos.get(i))); + } + return ManualLottos; + } + + private List<Lotto> issueAutoLottos(int numberOfAutoLottos) { + List<Lotto> autoLottos = new ArrayList<>(); + for (int i = 0; i < numberOfAutoLottos; i++) { + autoLottos.add(LottoGenerator.generateAutoLotto()); + } + return autoLottos; + } +}
Java
๋ณ€์ˆ˜๋ช…์ด ๋Œ€๋ฌธ์ž๋กœ ์‹œ์ž‘ํ•˜๋„ค์š” ~
@@ -0,0 +1,25 @@ +package lottodomain; + +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +public class LottoGenerator { + private static final List<Integer> LOTTO_NO_POOLS = IntStream.rangeClosed(1, 45).boxed().collect(Collectors.toList()); + ; + + public static Lotto generateLottoWithNos(List<Integer> lottoNos) { + return new Lotto(lottoNos); + } + + public static Lotto generateAutoLotto() { + return generateLottoWithNos(getRandomNos()); + } + + + private static List<Integer> getRandomNos() { + Collections.shuffle(LOTTO_NO_POOLS); + return LOTTO_NO_POOLS.subList(0, 6); + } +}
Java
Lotto ์— factory method ์„ ์ถ”๊ฐ€ํ•˜์—ฌ ์ƒ์„ฑํ•ด๋ณด๋ฉด ์–ด๋–จ๊นŒ์š”? ex> Lotto.ofAuto(), Lotto.ofManual("1,2,3,4,5,6)
@@ -0,0 +1,25 @@ +package lottodomain; + +public class LottoNo { + private Integer value; + + public LottoNo(int number) { + value = number; + } + + public Integer getValue() { + return value; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + LottoNo lottoNo = (LottoNo) o; + return value == lottoNo.value; + } +}
Java
LottoNo ๋ฅผ ์ƒ์„ฑํ•  ๋•Œ range ์— ๋Œ€ํ•œ ์กฐ๊ฑด์„ ๊ฒ€์ฆํ•˜๋ฉด ์ข€ ๋” ์˜๋ฏธ ์žˆ๋Š” wrapping class ๊ฐ€ ๋˜์ง€ ์•Š์„๊นŒ์š”?
@@ -0,0 +1,25 @@ +package lottodomain; + +public class LottoNo { + private Integer value; + + public LottoNo(int number) { + value = number; + } + + public Integer getValue() { + return value; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + LottoNo lottoNo = (LottoNo) o; + return value == lottoNo.value; + } +}
Java
๋ฌธ์ œ : "๋ชจ๋“  ์›์‹œ๊ฐ’๊ณผ ๋ฌธ์ž์—ด์„ ํฌ์žฅํ•œ๋‹ค." ์›์น™์— ๋”ฐ๋ผ ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑํ•˜๋‹ค๋ณด๋‹ˆ ๋„ˆ๋ฌด ๋งŽ์€ ๊ฐ์ฒด๊ฐ€ ์ƒ์„ฑ๋˜๊ณ , GC๊ฐ€ ๋˜์–ด ์„ฑ๋Šฅ์ƒ ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค. ํŠนํžˆ ๋กœ๋˜ ๋ฒˆํ˜ธ ํ•˜๋‚˜๊นŒ์ง€ ๊ฐ์ฒด๋กœ ํฌ์žฅํ•  ๊ฒฝ์šฐ ์ƒ์„ฑ๋˜๋Š” ์ธ์Šคํ„ด์Šค์˜ ์ˆ˜๋Š” ์ƒ๋‹นํžˆ ๋Š˜์–ด๋‚˜๋Š” ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค. ์œ„์™€ ๊ฐ™์€ ๋ฌธ์ œ๋Š” ์–ด๋–ป๊ฒŒ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์„๊นŒ์š”? (ํ‚ค์›Œ๋“œ : static, map)
@@ -0,0 +1,25 @@ +package lottodomain; + +public class LottoNo { + private Integer value; + + public LottoNo(int number) { + value = number; + } + + public Integer getValue() { + return value; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + LottoNo lottoNo = (LottoNo) o; + return value == lottoNo.value; + } +}
Java
๋ถˆ๋ณ€์˜ ๊ฐ’์„ wrapping ํ•œ ํด๋ž˜์Šค์ด๋ฏ€๋กœ final int value; ๋กœ ์„ ์–ธํ•ด๋ณด๋ฉด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,49 @@ +package lottoview; + +import lottodomain.Lotto; +import lottodomain.LottoAnalyzer; +import lottodomain.LottoNo; +import lottodomain.Rank; + +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class OutputView { + public static void showAllLottos(List<Lotto> allLotto, int numberOfManualLottos) { + int numberOfAutoLottos = allLotto.size() - numberOfManualLottos; + System.out.printf("์ˆ˜๋™์œผ๋กœ %d์žฅ, ์ž๋™์œผ๋กœ %d์žฅ์„ ๊ตฌ๋งคํ–ˆ์Šต๋‹ˆ๋‹ค.\n", numberOfManualLottos, numberOfAutoLottos); + allLotto.stream().forEach(lotto -> showLotto(lotto)); + } + + public static void showLotto(Lotto lotto) { + List<LottoNo> lottoNos = lotto.getLottoNos(); + System.out.println(lottoNos.stream().map(LottoNo::getValue).map(number -> number.toString()) + .collect(Collectors.joining(", ", "[", "]"))); + } + + public static void showAnalysis(LottoAnalyzer lottoAnalyzer) { + showWRanks(lottoAnalyzer); + showEarningRate(lottoAnalyzer.calculateEarningRate()); + } + + public static void showRankCount(Rank rank, int count) { + System.out.printf("%d๊ฐœ ์ผ์น˜ (%d์›)- %d๊ฐœ\n", rank.getCountOfMatch(), rank.getWinningMoney(), count); + } + + public static void showEarningRate(double earningRate) { + System.out.printf("์ด ์ˆ˜์ต๋ฅ ์€ %.1f%%์ž…๋‹ˆ๋‹ค.\n", earningRate); + } + + private static void showWRanks(LottoAnalyzer lottoAnalyzer) { + System.out.println("๋‹น์ฒจ ํ†ต๊ณ„"); + System.out.println("---------"); + List<Rank> prize = Stream.of(Rank.values()).collect(Collectors.toList()); + prize.remove(Rank.MISS); + for (int i = prize.size() - 1; i >= 0; i--) { + int count = lottoAnalyzer.countRank(prize.get(i)); + showRankCount(prize.get(i), count); + } + } +}
Java
analyzer ๊ฐ€ outputview ์— ์™€์„œ ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง์„ ์ˆ˜ํ–‰ํ•˜๊ณ  ์žˆ๋Š”๋ฐ์š” ๊ฒŒ์ž„์˜ ๊ฒฐ๊ณผ๋ฅผ ๋‹ด๋Š” LottoResults(DTO) ํด๋ž˜์Šค์™€ Lotto list ๋ฅผ ๊ฐ์‹ธ๋Š” Lottos ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“ค์–ด์„œ outputview ์—์„œ ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง์ด ์‹คํ–‰๋˜์ง€ ์•Š๋„๋ก ๋ณ€๊ฒฝํ•ด๋ณด๋ฉด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,63 @@ +package lottodomain; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.*; + +public class LottoAnalyzerTest { + private static final double DELTA = 1e-15; + + private List<Lotto> lottos; + private LottoAnalyzer lottoAnalyzer; + private WinningNos winningNos; + + @Before + public void setUp() throws Exception { + lottos = new ArrayList<>(); + lottos.add(new Lotto(Arrays.asList(1, 2, 3, 4, 5, 6))); // FIRST + lottos.add(new Lotto(Arrays.asList(1, 2, 3, 4, 5, 7))); // SECOND + lottos.add(new Lotto(Arrays.asList(1, 2, 3, 4, 5, 8))); // THIRD + lottos.add(new Lotto(Arrays.asList(1, 2, 3, 4, 7, 8))); // FOURTH + lottos.add(new Lotto(Arrays.asList(1, 2, 3, 7, 8, 9))); // FIFTH + lottos.add(new Lotto(Arrays.asList(1, 2, 7, 8, 9, 10))); // MISS + winningNos = new WinningNos(Arrays.asList(1, 2, 3, 4, 5, 6), 7); + lottoAnalyzer = new LottoAnalyzer(lottos, winningNos); + } + + @Test + public void calculateRankOfLotto() { + List<Rank> ranks = Arrays.asList(Rank.values()); + for (int i = 0; i < lottos.size(); i++) { + assertEquals(ranks.get(i), lottoAnalyzer.calculateRankOfLotto(lottos.get(i), winningNos)); + } + } + + @Test + public void calculateEarnedMoney() { + assertEquals(2031555000, lottoAnalyzer.calculateEarnedMoney()); + } + + @Test + public void calculateEarningRate() { + assertEquals(33859250.0, lottoAnalyzer.calculateEarningRate(), DELTA); + } + + @Test + public void countRank() { + List<Rank> ranks = Arrays.asList(Rank.values()); + for (int i = 0; i < ranks.size(); i++) { + assertEquals(1, lottoAnalyzer.countRank(ranks.get(i))); + } + } + + @After + public void tearDown() throws Exception { + lottos = null; + } +} \ No newline at end of file
Java
์ข‹์€ ์œ ๋‹›ํ…Œ์ŠคํŠธ ์ž‘์„ฑ๋ฒ•์—๋Š” F.I.R.S.T ๋ผ๋Š” ์›์น™์ด ์žˆ๋Š”๋ฐ์š” https://coding-start.tistory.com/261 ์ฒจ๋ถ€ํ•˜๊ณ  ๊ฐ‘๋‹ˆ๋‹ค ~
@@ -0,0 +1,47 @@ +package lottodomain; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.junit.Assert.*; + +public class LottoGameTest { + private LottoGame lottoGame; + List<List<Integer>> manualLottoNumbers; + + private void assertArrayEquals(List<Lotto> expectedLottos, List<Lotto> subList) { + for (int i = 0; i < expectedLottos.size(); i++) { + assertEquals(expectedLottos.get(i), subList.get(i)); + } + } + + @Before + public void setUp() throws Exception { + manualLottoNumbers = new ArrayList<>(); + manualLottoNumbers.add(Arrays.asList(1, 2, 3, 4, 5, 6)); + manualLottoNumbers.add(Arrays.asList(1, 4, 11, 15, 19, 23)); + manualLottoNumbers.add(Arrays.asList(4, 10, 17, 25, 34, 42)); + } + + @Test + public void setManualLottos() { + lottoGame = new LottoGame(10000, manualLottoNumbers); + assertEquals(10, lottoGame.getAllLotto().size()); + + List<Lotto> expectedLottos = manualLottoNumbers.stream().map(numbers -> LottoGenerator.generateLottoWithNos(numbers)) + .collect(Collectors.toList()); + assertArrayEquals(expectedLottos, lottoGame.getAllLotto().subList(0, 3)); + } + + @After + public void tearDown() throws Exception { + lottoGame = null; + manualLottoNumbers = null; + } +} \ No newline at end of file
Java
private method ๋Š” public ๋ณด๋‹ค ์•„๋ž˜์— ์œ„์น˜์‹œ์ผœ์ฃผ๋Š”๊ฒŒ ๊ฐ€๋…์„ฑ์— ์ข‹์Šต๋‹ˆ๋‹ค ~
@@ -0,0 +1,50 @@ +package lottodomain; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.*; + +public class WinningNosTest { + private WinningNos winningNos; + + @Before + public void setUp() throws Exception { + winningNos = new WinningNos(Arrays.asList(1, 2, 3, 4, 5, 6), 7); + } + + @Test + public void countMatchOf() { + List<Lotto> lottos = new ArrayList<>(); + lottos.add(new Lotto(Arrays.asList(8, 9, 10, 11, 12, 13))); + lottos.add(new Lotto(Arrays.asList(1, 8, 9, 10, 11, 12))); + lottos.add(new Lotto(Arrays.asList(1, 2, 9, 10, 11, 12))); + lottos.add(new Lotto(Arrays.asList(1, 2, 3, 10, 11, 12))); + lottos.add(new Lotto(Arrays.asList(1, 2, 3, 4, 11, 12))); + lottos.add(new Lotto(Arrays.asList(1, 2, 3, 4, 5, 12))); + lottos.add(new Lotto(Arrays.asList(1, 2, 3, 4, 5, 6))); + + for (int i = 0; i < lottos.size(); i++) { + assertEquals(i, winningNos.countMatchOf(lottos.get(i))); + } + } + + @Test + public void isBonus() { + Lotto trueLotto = new Lotto(Arrays.asList(1, 2, 3, 4, 5, 6, 7)); + Lotto falseLotto = new Lotto(Arrays.asList(1, 2, 3, 4, 5, 6, 8)); + + assertTrue(winningNos.isBonus(trueLotto)); + assertFalse(winningNos.isBonus(falseLotto)); + } + + @After + public void tearDown() throws Exception { + winningNos = null; + } +} \ No newline at end of file
Java
์ „์ฒด์ ์œผ๋กœ ์ฝ”๋“œ์— ๋น„ํ•ด ํ…Œ์ŠคํŠธ ์ชฝ์ด ์กฐ๊ธˆ ์•„์‰ฌ์›Œ์„œ ์‹œ๊ฐ„์ด ๋˜์‹ ๋‹ค๋ฉด TDD ๋ฐฉ๋ฒ•๋ก ์„ ํ†ตํ•ด ๋กœ๋˜๋‚˜ ๋ ˆ์ด์‹ฑ ๊ฒŒ์ž„์„ ๋‹ค์‹œ ๊ตฌํ˜„ํ•ด๋ณด๋Š” ๊ฒƒ๋„ ๋งŽ์ด ๋„์›€์ด ๋˜์‹ค ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,62 @@ +package nextstep.app; + +import nextstep.app.domain.Member; +import nextstep.app.domain.MemberRepository; +import nextstep.security.DefaultSecurityFilterChain; +import nextstep.security.FilterChainProxy; +import nextstep.security.SecurityFilterChain; +import nextstep.security.filter.BasicAuthenticationFilter; +import nextstep.security.filter.FormLoginAuthenticationFilter; +import nextstep.security.UserDetails; +import nextstep.security.UserDetailsService; +import nextstep.security.util.matcher.AnyRequestMatcher; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.filter.DelegatingFilterProxy; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import java.util.List; + +@Configuration +public class FilterConfig implements WebMvcConfigurer { + + private final MemberRepository memberRepository; + + public FilterConfig(MemberRepository memberRepository) { + this.memberRepository = memberRepository; + } + + @Bean + public DelegatingFilterProxy delegatingFilterProxy() { + return new DelegatingFilterProxy(filterChainProxy()); + } + + private FilterChainProxy filterChainProxy() { + return new FilterChainProxy(securityFilterChain()); + } + + private SecurityFilterChain securityFilterChain() { + return new DefaultSecurityFilterChain(AnyRequestMatcher.INSTANCE, List.of( + new BasicAuthenticationFilter(userDetailsService()), + new FormLoginAuthenticationFilter(userDetailsService()) + )); + } + + private UserDetailsService userDetailsService() { + return username -> { + Member member = memberRepository.findByEmail(username) + .orElseThrow(() -> new IllegalArgumentException("ํ•ด๋‹นํ•˜๋Š” ์‚ฌ์šฉ์ž๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")); + return new UserDetails() { + @Override + public String getUsername() { + return member.getEmail(); + } + + @Override + public String getPassword() { + return member.getPassword(); + } + }; + }; + } +}
Java
```suggestion UserDetailsService userDetailsService = userDetailsService(); return new DefaultSecurityFilterChain(AnyRequestMatcher.INSTANCE, List.of( new BasicAuthenticationFilter(userDetailsService), new FormLoginAuthenticationFilter(userDetailsService) )); ``` ๊ฐ์ฒด๋ฅผ ๋‘๋ฒˆ ์ƒ์„ฑํ•˜์ง€ ์•Š๊ณ  ๋ณ€์ˆ˜๋กœ ๋นผ์„œ ํ•œ๋ฒˆ๋งŒ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋„๋ก ๋ณ€๊ฒฝํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š” :)
@@ -1,4 +1,4 @@ -package nextstep.app.ui; +package nextstep.security; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus;
Java
๊ฐ ํด๋ž˜์Šค๋Š” ๋‹จ์ˆœํžˆ security ํŒจํ‚ค์ง€๋ณด๋‹ค๋Š” ๊ทธ ํด๋ž˜์Šค๋“ค์— ๋งž๋Š” ํŒจํ‚ค์ง€๋ฅผ ๊ณ ๋ คํ•ด๋ณด๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”. spring security๋ฅผ ์ฐธ๊ณ ํ•˜์…”๋„ ์ข‹๊ณ , ์˜ˆ๋ฅผ ๋“ค๋ฉด ์ด ํด๋ž˜์Šค๋Š” ์ธ์ฆ๊ด€๋ จ๋œ ์˜ˆ์™ธ ํด๋ž˜์Šค์ด๋‹ˆ `authentication`์ด๋ผ๋Š” ํŒจํ‚ค์ง€๊ฐ€ ๋” ์–ด์šธ๋ ค๋ณด์ด๋„ค์š”.
@@ -0,0 +1,34 @@ +package nextstep.security; + +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.web.filter.GenericFilterBean; + +import java.io.IOException; +import java.util.List; + +public class FilterChainProxy extends GenericFilterBean { + + private final SecurityFilterChain securityFilterChain; + + public FilterChainProxy(SecurityFilterChain securityFilterChain) { + this.securityFilterChain = securityFilterChain; + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + + HttpServletRequest request = (HttpServletRequest) servletRequest; + HttpServletResponse response = (HttpServletResponse) servletResponse; + + List<Filter> filters = securityFilterChain.getFilters(); + + var virtualFilterChain = new VirtualFilterChain(filters, filterChain); + virtualFilterChain.doFilter(request, response); + } +}
Java
`FilterChainProxy`๋Š” ํ•˜๋‚˜์˜ `FilterChain`๋งŒ ๊ฐ€์ง€๊ณ  ์žˆ์ง€ ์•Š์Šต๋‹ˆ๋‹ค. 1๋‹จ๊ณ„ ์ด๋ฏธ์ง€์— ๋‚˜์™€์žˆ๋Š” ๊ฒƒ์ฒ˜๋Ÿผ `FilterChainProxy`๊ฐ€ ์—ฌ๋Ÿฌ `SecurityFilterChain`์„ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ํ˜•ํƒœ๋กœ ๋ณ€๊ฒฝํ•ด์ฃผ์„ธ์š” :)
@@ -0,0 +1,31 @@ +package nextstep.security; + +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; + +import java.io.IOException; +import java.util.List; + +public class VirtualFilterChain implements FilterChain { + + private final List<Filter> filters; + private final FilterChain originalChain; + private int currentPosition = 0; + + public VirtualFilterChain(List<Filter> filters, FilterChain originalChain) { + this.filters = filters; + this.originalChain = originalChain; + } + + public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { + if (this.currentPosition == filters.size()) { + this.originalChain.doFilter(request, response); + } else { + Filter nextFilter = filters.get(currentPosition++); + nextFilter.doFilter(request, response, this); + } + } +}
Java
```suggestion if (this.currentPosition == filters.size()) { this.originalChain.doFilter(request, response); return; } Filter nextFilter = filters.get(currentPosition++); nextFilter.doFilter(request, response, this); ``` else ๋ฌธ์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ์›์น™ ์™ธ์—๋„ ๊ฐ€์‹œ์„ฑ์„ ์œ„ํ•ด์„œ ์ข…๋ฃŒ์‹œ์ ์— return์ž„์„ ๋ช…์‹œํ•ด์ฃผ๋Š” ๊ฒƒ์ด ํ•ด๋‹น ์ฝ”๋“œ์˜ ๊ฐ€๋…์„ฑ์„ ์˜ฌ๋ฆฌ๋Š”๋ฐ ๋„์›€์„ ์ค„ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”.
@@ -0,0 +1,13 @@ +package nextstep.security.util.matcher; + +import jakarta.servlet.http.HttpServletRequest; + +public class AnyRequestMatcher implements RequestMatcher { + + public static final AnyRequestMatcher INSTANCE = new AnyRequestMatcher(); + + @Override + public boolean matches(HttpServletRequest request) { + return true; + } +}
Java
๊ฐœ์ธ์ ์œผ๋กœ ์‹ฑ๊ธ€ํ†ค์œผ๋กœ ๋งŒ๋“ค ํ•„์š”๋Š” ๋”ฐ๋กœ ์—†์–ด๋ณด์ด๊ณ , ์‹ฑ๊ธ€ํ†ค์ด์–ด์•ผํ•œ๋‹ค๋ฉด ์ƒ์„ฑ์ž๋ฅผ private์œผ๋กœ ๋ง‰๋Š” ๊ฒƒ์ด ์ข‹์•„๋ณด์ด๋„ค์š” ๐Ÿ˜„
@@ -0,0 +1,58 @@ +package nextstep.security.filter; + +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.AuthenticationException; +import nextstep.security.util.Base64Convertor; +import nextstep.security.UserDetails; +import nextstep.security.UserDetailsService; +import nextstep.security.util.matcher.MvcRequestMatcher; +import org.springframework.http.HttpMethod; + +import java.io.IOException; + +public class BasicAuthenticationFilter implements Filter { + + private static final MvcRequestMatcher DEFAULT_REQUEST_MATCHER = new MvcRequestMatcher(HttpMethod.GET, "/members"); + + private final UserDetailsService userDetailsService; + + public BasicAuthenticationFilter(UserDetailsService userDetailsService) { + this.userDetailsService = userDetailsService; + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + if (!DEFAULT_REQUEST_MATCHER.matches((HttpServletRequest) servletRequest)) { + filterChain.doFilter(servletRequest, servletResponse); + return; + } + + HttpServletRequest request = (HttpServletRequest) servletRequest; + HttpServletResponse response = (HttpServletResponse) servletResponse; + + try { + String authorization = request.getHeader("Authorization"); + String credentials = authorization.split(" ")[1]; + String decodedString = Base64Convertor.decode(credentials); + String[] usernameAndPassword = decodedString.split(":"); + String username = usernameAndPassword[0]; + String password = usernameAndPassword[1]; + + UserDetails userDetails = userDetailsService.loadUserByUsername(username); + if (!userDetails.getPassword().equals(password)) { + throw new AuthenticationException(); + } + + filterChain.doFilter(servletRequest, servletResponse); + + } catch (Exception e) { + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + } + } +}
Java
2๋‹จ๊ณ„๋ฅผ ์ฐธ๊ณ ํ•˜์—ฌ ์–ด๋–ค ์ฑ…์ž„๋“ค์ด `Filter`์—์„œ ๋น ์ ธ์•ผํ•˜๋Š”์ง€ ๊ณ ๋ฏผํ•ด๋ณด์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”. `Filter`์˜ ์ฑ…์ž„์€ request ์š”์ฒญ์„ ๋ฐ›์•„ ์ฒ˜๋ฆฌ๊ฐ€ ๊ฐ€๋Šฅํ•œ์ง€ ํ™•์ธํ•˜๊ณ , ๊ฒฐ๊ณผ์— ๋Œ€ํ•œ ํ•„ํ„ฐ๋ง์„ ํ•˜๋Š”๋ฐ ์ด๊ฒƒ๋งŒ์œผ๋กœ๋„ ์ฑ…์ž„์ด ํฌ๊ธฐ ๋•Œ๋ฌธ์— 2๋‹จ๊ณ„์—์„œ ๋‚˜์˜ค๋Š” ํด๋ž˜์Šค๋“ค์—๊ฒŒ ์ฑ…์ž„์„ ์œ„์ž„ํ•œ๋‹ค๊ณ  ๋ณด์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,58 @@ +package nextstep.security.filter; + +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.AuthenticationException; +import nextstep.security.util.Base64Convertor; +import nextstep.security.UserDetails; +import nextstep.security.UserDetailsService; +import nextstep.security.util.matcher.MvcRequestMatcher; +import org.springframework.http.HttpMethod; + +import java.io.IOException; + +public class BasicAuthenticationFilter implements Filter { + + private static final MvcRequestMatcher DEFAULT_REQUEST_MATCHER = new MvcRequestMatcher(HttpMethod.GET, "/members"); + + private final UserDetailsService userDetailsService; + + public BasicAuthenticationFilter(UserDetailsService userDetailsService) { + this.userDetailsService = userDetailsService; + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + if (!DEFAULT_REQUEST_MATCHER.matches((HttpServletRequest) servletRequest)) { + filterChain.doFilter(servletRequest, servletResponse); + return; + } + + HttpServletRequest request = (HttpServletRequest) servletRequest; + HttpServletResponse response = (HttpServletResponse) servletResponse; + + try { + String authorization = request.getHeader("Authorization"); + String credentials = authorization.split(" ")[1]; + String decodedString = Base64Convertor.decode(credentials); + String[] usernameAndPassword = decodedString.split(":"); + String username = usernameAndPassword[0]; + String password = usernameAndPassword[1]; + + UserDetails userDetails = userDetailsService.loadUserByUsername(username); + if (!userDetails.getPassword().equals(password)) { + throw new AuthenticationException(); + } + + filterChain.doFilter(servletRequest, servletResponse); + + } catch (Exception e) { + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + } + } +}
Java
์–ด๋–ค path๋กœ ์š”์ฒญ๋˜๋Š” ์ง€์— ๋Œ€ํ•ด์„œ ๊ฐ์ฒด์— ์ƒ์ˆ˜๋กœ ๊ณ ์ •ํ•˜์—ฌ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹Œ ์‚ฌ์šฉ์ž์—๊ฒŒ ์ฃผ์ž…๋ฐ›์•„ ์ƒ์„ฑํ•˜๋Š” ๊ฒƒ์ด `BasicAuthenticationFilter`์˜ ์žฌ์‚ฌ์šฉ์„ฑ์— ๋„์›€์„ ์ค„ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”.
@@ -0,0 +1,60 @@ +package nextstep.security.filter; + +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; +import nextstep.security.AuthenticationException; +import nextstep.security.UserDetails; +import nextstep.security.UserDetailsService; +import nextstep.security.util.matcher.MvcRequestMatcher; +import org.springframework.http.HttpMethod; + +import java.io.IOException; +import java.util.Map; + +public class FormLoginAuthenticationFilter implements Filter { + + public static final String SPRING_SECURITY_CONTEXT_KEY = "SPRING_SECURITY_CONTEXT"; + private static final MvcRequestMatcher DEFAULT_REQUEST_MATCHER = new MvcRequestMatcher(HttpMethod.POST, "/login"); + + private final UserDetailsService userDetailsService; + + public FormLoginAuthenticationFilter(UserDetailsService userDetailsService) { + this.userDetailsService = userDetailsService; + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + if (!DEFAULT_REQUEST_MATCHER.matches((HttpServletRequest) servletRequest)) { + filterChain.doFilter(servletRequest, servletResponse); + return; + } + + HttpServletRequest request = (HttpServletRequest) servletRequest; + HttpServletResponse response = (HttpServletResponse) servletResponse; + + try { + Map<String, String[]> parameterMap = request.getParameterMap(); + String username = parameterMap.get("username")[0]; + String password = parameterMap.get("password")[0]; + + UserDetails userDetails = userDetailsService.loadUserByUsername(username); + if (!userDetails.getPassword().equals(password)) { + throw new AuthenticationException(); + } + + HttpSession session = request.getSession(); + session.setAttribute(SPRING_SECURITY_CONTEXT_KEY, userDetails); + + filterChain.doFilter(servletRequest, servletResponse); + + } catch (Exception e) { + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + } + } +}
Java
```suggestion private static final String SPRING_SECURITY_CONTEXT_KEY = "SPRING_SECURITY_CONTEXT"; ``` ์ ‘๊ทผ์„ ๋ง‰์•„๋„ ๋  ๊ฒƒ ๊ฐ™๋„ค์š”.
@@ -1,5 +1,98 @@ import React from 'react'; +import { useState, useEffect } from 'react'; +import { useNavigate } from 'react-router-dom'; +import './Login.scss'; -export default function Login() { - return <div>Hello, Hyeonze!</div>; -} +const Login = () => { + const [idInput, setIdInput] = useState(''); + const [pwInput, setPwInput] = useState(''); + const [isValidatedUser, setIsValidatedUser] = useState(false); + + const navigate = useNavigate(); + const changeIdInput = e => { + const { value } = e.target; + setIdInput(value); + }; + + const changePwInput = e => { + const { value } = e.target; + setPwInput(value); + }; + + useEffect(() => { + setIsValidatedUser(idInput.indexOf('@') !== -1 && pwInput.length > 4); + }, [idInput, pwInput]); + + // ๋ฉ”์ธ์œผ๋กœ ์ด๋™ํ•  ๋•Œ ๋กœ์ง + const goToMain = () => { + navigate('/main-hyeonze'); + }; + + // ํšŒ์›๊ฐ€์ž…์‹œ ์‚ฌ์šฉํ•  ๋กœ์ง + // const signup = () => { + // fetch('http://10.58.4.22:8000/users/signup', { + // method: 'POST', + // body: JSON.stringify({ + // email: idInput, + // password: pwInput, + // }), + // }) + // .then(response => response.json()) + // .then(result => { + // //console.log('๊ฒฐ๊ณผ: ', result.message) + // if (result.message === 'EMAIL_ALREADY_EXISTS') { + // console.log('Error : Duplicated'); + // } + // }); + // }; + + // ๋กœ๊ทธ์ธ์‹œ ์‚ฌ์šฉํ•  ๋กœ์ง + // const login = () => { + // fetch('http://10.58.4.22:8000/users/login', { + // method: 'POST', + // body: JSON.stringify({ + // email: idInput, + // password: pwInput, + // }), + // }) + // .then(response => response.json()) + // .then(result => { + // //console.log('๊ฒฐ๊ณผ: ', result.message) + // if (result.message === 'SUCCESS') { + // console.log('login SUCCESS'); + // } + // }); + // }; + + return ( + <div className="login"> + <div id="wrapper"> + <h1>westagram</h1> + <form className="login_form"> + <input + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + className="username" + onChange={changeIdInput} + /> + <input + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + className="userpassword" + onChange={changePwInput} + /> + <input + className={isValidatedUser ? 'activated' : ''} + disabled={!isValidatedUser} + type="button" + value="๋กœ๊ทธ์ธ" + onClick={goToMain} + /> + </form> + <p>๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</p> + </div> + </div> + ); +}; + +export default Login;
Unknown
์ด ๋‘ ์กฐ๊ฑด์„ &&๋กœ ๊ฑธ๋ฉด state๋ฅผ ํ•˜๋‚˜๋งŒ ์‚ฌ์šฉํ•˜๊ณ  validation์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ์ง€ ์•Š์„๊นŒ์š”? ์™œ ์œ ์ฆˆ์ดํŽ™ํŠธ๋ฅผ ์“ฐ์…จ๋Š”์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค.
@@ -1,5 +1,98 @@ import React from 'react'; +import { useState, useEffect } from 'react'; +import { useNavigate } from 'react-router-dom'; +import './Login.scss'; -export default function Login() { - return <div>Hello, Hyeonze!</div>; -} +const Login = () => { + const [idInput, setIdInput] = useState(''); + const [pwInput, setPwInput] = useState(''); + const [isValidatedUser, setIsValidatedUser] = useState(false); + + const navigate = useNavigate(); + const changeIdInput = e => { + const { value } = e.target; + setIdInput(value); + }; + + const changePwInput = e => { + const { value } = e.target; + setPwInput(value); + }; + + useEffect(() => { + setIsValidatedUser(idInput.indexOf('@') !== -1 && pwInput.length > 4); + }, [idInput, pwInput]); + + // ๋ฉ”์ธ์œผ๋กœ ์ด๋™ํ•  ๋•Œ ๋กœ์ง + const goToMain = () => { + navigate('/main-hyeonze'); + }; + + // ํšŒ์›๊ฐ€์ž…์‹œ ์‚ฌ์šฉํ•  ๋กœ์ง + // const signup = () => { + // fetch('http://10.58.4.22:8000/users/signup', { + // method: 'POST', + // body: JSON.stringify({ + // email: idInput, + // password: pwInput, + // }), + // }) + // .then(response => response.json()) + // .then(result => { + // //console.log('๊ฒฐ๊ณผ: ', result.message) + // if (result.message === 'EMAIL_ALREADY_EXISTS') { + // console.log('Error : Duplicated'); + // } + // }); + // }; + + // ๋กœ๊ทธ์ธ์‹œ ์‚ฌ์šฉํ•  ๋กœ์ง + // const login = () => { + // fetch('http://10.58.4.22:8000/users/login', { + // method: 'POST', + // body: JSON.stringify({ + // email: idInput, + // password: pwInput, + // }), + // }) + // .then(response => response.json()) + // .then(result => { + // //console.log('๊ฒฐ๊ณผ: ', result.message) + // if (result.message === 'SUCCESS') { + // console.log('login SUCCESS'); + // } + // }); + // }; + + return ( + <div className="login"> + <div id="wrapper"> + <h1>westagram</h1> + <form className="login_form"> + <input + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + className="username" + onChange={changeIdInput} + /> + <input + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + className="userpassword" + onChange={changePwInput} + /> + <input + className={isValidatedUser ? 'activated' : ''} + disabled={!isValidatedUser} + type="button" + value="๋กœ๊ทธ์ธ" + onClick={goToMain} + /> + </form> + <p>๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</p> + </div> + </div> + ); +}; + +export default Login;
Unknown
id์™€ pw๋กœ ํ•œ๋ฒˆ์— validationํ•˜๊ณ  activateBtn์— True/false๋ฅผ ์ง€์ •ํ•˜๋ฉด ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. isValidatedId๋‚˜ isValidatedPw๋Š” ํฌ๊ฒŒ ํ•„์š”ํ•˜์ง€ ์•Š์„ ๊ฒƒ ๊ฐ™์•„์š”. ๋ถˆํ•„์š”ํ•œ ๋ฆฌ๋žœ๋”๋ง๋„ ์ค„์ผ ์ˆ˜ ์žˆ๋‹ค๊ณ  ์ƒ๊ฐํ•˜๋Š”๋ฐ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”?
@@ -0,0 +1,66 @@ +@use '../../../styles/mixin.scss' as mixin; +@use '../../../styles/color.scss' as clr; + +body { + background: clr.$bg-login; + + .login { + position: relative; + top: -80px; + + #wrapper { + @include mixin.flex($align: center); + position: relative; + flex-direction: column; + width: 700px; + height: 761px; + border: 1px solid clr.$clr-border; + + h1 { + margin-top: 90px; + margin-bottom: 130px; + font-size: 81px; + font-family: 'Lobster', cursive; + } + + .login_form { + input { + display: block; + width: 536px; + height: 76px; + margin-bottom: 12px; + padding-left: 10px; + background: #fafafa; + border: 1px solid clr.$clr-border; + border-radius: 3px; + font-size: 16px; + } + + input[type='button'] { + display: flex; + align-items: center; + justify-content: center; + width: 536px; + height: 60px; + margin-top: 16px; + background-color: clr.$clr-primary; + opacity: 0.5; + border: none; + border-radius: 4px; + font-size: 16px; + color: #fff; + + &.activated { + opacity: 1; + } + } + } + + p { + position: absolute; + bottom: 20px; + color: #043667; + } + } + } +}
Unknown
input์ด inline-block์ด๊ณ  ์ˆ˜์ง์œผ๋กœ ์ •๋ ฌํ•˜๋ ค๊ณ  display: flex๋ฅผ ์“ฐ์‹  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๊ต‰์žฅํžˆ ์ข‹์€๋ฐ์š” ์ €๋Š” Input์„ display: blockํ•ด์ฃผ๋Š” ๊ฒƒ๋„ ๊ดœ์ฐฎ์€ ๋ฐฉ๋ฒ•์ด์ง€ ์•Š์„๊นŒ ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,66 @@ +@use '../../../styles/mixin.scss' as mixin; +@use '../../../styles/color.scss' as clr; + +body { + background: clr.$bg-login; + + .login { + position: relative; + top: -80px; + + #wrapper { + @include mixin.flex($align: center); + position: relative; + flex-direction: column; + width: 700px; + height: 761px; + border: 1px solid clr.$clr-border; + + h1 { + margin-top: 90px; + margin-bottom: 130px; + font-size: 81px; + font-family: 'Lobster', cursive; + } + + .login_form { + input { + display: block; + width: 536px; + height: 76px; + margin-bottom: 12px; + padding-left: 10px; + background: #fafafa; + border: 1px solid clr.$clr-border; + border-radius: 3px; + font-size: 16px; + } + + input[type='button'] { + display: flex; + align-items: center; + justify-content: center; + width: 536px; + height: 60px; + margin-top: 16px; + background-color: clr.$clr-primary; + opacity: 0.5; + border: none; + border-radius: 4px; + font-size: 16px; + color: #fff; + + &.activated { + opacity: 1; + } + } + } + + p { + position: absolute; + bottom: 20px; + color: #043667; + } + } + } +}
Unknown
'๋กœ๊ทธ์ธ' ์ด๋ผ๋Š” ๊ธ€์ž ์„ผํ„ฐ์— ๋งž์ถ”๊ธฐ ์œ„ํ•ด display: flex์ฃผ์‹  ๊ฒƒ ๊ฐ™์•„์š”. ์ข‹์€๋ฐฉ๋ฒ•์ด์ง€๋งŒ flex์™€ ๊ทธ ์†์„ฑ๋“ค์ด ์ข€ ๋–จ์–ด์ ธ ์žˆ๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์ด๋ ‡๊ฒŒ ์—ฐ๊ด€๋˜๋Š” css์†์„ฑ์€ ๋ถ™์—ฌ ์ฃผ์‹œ๋Š” ๊ฒŒ ๋‚˜์ค‘์— ์œ ์ง€๋ณด์ˆ˜ ์ธก๋ฉด์—์„œ๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„ ์ถ”์ฒœ ๋“œ๋ฆฝ๋‹ˆ๋‹ค!
@@ -0,0 +1,26 @@ +import React, { useState } from 'react'; +import { AiFillDelete, AiOutlineHeart, AiFillHeart } from 'react-icons/ai'; + +const Comment = ({ id, userId, value, time, handleDelete }) => { + const [isLiked, setIsLiked] = useState(false); + + const toggleLike = () => { + setIsLiked(!isLiked); + }; + + return ( + <span id={id} className="comment"> + <strong>{userId} </strong> + {value} + <small> {time}</small> + <AiFillDelete onClick={handleDelete} className="delete" /> + {isLiked ? ( + <AiFillHeart onClick={toggleLike} className="hearts liked" /> + ) : ( + <AiOutlineHeart onClick={toggleLike} className="hearts" /> + )} + </span> + ); +}; + +export default Comment;
Unknown
์ €๋ฒˆ ์„ธ์…˜์—์„œ ๋ฉ˜ํ† ๋‹˜์ด ํ•˜์‹  ๊ฒƒ์ฒ˜๋Ÿผ ๋ณ€์ˆ˜๋ช…์„ ์กฐ๊ธˆ ๋” ๊ตฌ์ฒด์ ์œผ๋กœ ์–ด๋–ค ๋‚ด์šฉ์„ ๋‹ด๊ณ  ์žˆ๋Š”์ง€๋ฅผ ์ž‘์„ฑํ•ด ์ฃผ์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. commentVal์ด ๋Œ“๊ธ€ ์ „์ฒด๋ฅผ ๊ด€๋ฆฌํ•˜๋Š” ๋ฐฐ์—ด์ด๊ณ  el์ด ๊ฐ ๋ฐฐ์—ด์˜ ์š”์†Œ์ด๋‹ˆ๊น commentVal๋Œ€์‹  allComments, el๋Œ€์‹  comment๋“ฑ์œผ๋กœ (์ด๊ฑด ์ €๋„ ์กฐ๊ธˆ ์• ๋งคํ•˜๋„ค์š” .. ์ฃ„์†กํ•ฉ๋‹ˆ๋‹ค) (๋ฐฐ์—ด์€ s๋ฅผ ๋ถ™์ธ ๋ณ€์ˆ˜๋ช…์œผ๋กœ ํ•˜๋Š” ๊ฒŒ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!)
@@ -0,0 +1,43 @@ +span.comment { + padding-left: 10px; + + small { + color: #a3a3a3; + } + + &:first-child { + padding: 10px; + font-weight: bold; + } + + svg { + &.delete { + display: none; + cursor: pointer; + } + + &.hearts { + color: #a3a3a3; + position: absolute; + right: 20px; + transition: color 1s; + cursor: pointer; + + path { + color: #a3a3a3; + } + } + + &.liked { + path { + color: #f00; + } + } + } + + &:hover svg { + &.delete { + display: inline-block; + } + } +}
Unknown
span์— ๋Œ€ํ•ด์„œ๋งŒ ์Šคํƒ€์ผ๋ง์„ ํ•ด์ฃผ์…จ๋Š”๋ฐ ์ด๋Ÿฌ๋ฉด ๋‹ค๋ฅธ ์ปดํฌ๋„ŒํŠธ์˜ span์—๋„ ์˜ํ–ฅ์ด ๊ฐ€์ง€ ์•Š์„๊นŒ ์กฐ์‹ฌ์Šค๋Ÿฝ๊ฒŒ ์ƒ๊ฐํ•ด ๋ด…๋‹ˆ๋‹ค. ๊ฐœ์ธ์ ์œผ๋กœ className์„ ์ฃผ๋Š” ๊ฒŒ ์กฐ๊ธˆ ๋” ์•ˆ์ „ํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค ์ถ”๊ฐ€์ ์œผ๋กœ svgํƒœ๊ทธ๋„ span ๋‚ด๋ถ€์— nestingํ•ด์ฃผ์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”. ``` svg { &.red {} &.blue {} } ```
@@ -0,0 +1,87 @@ +import React, { useState } from 'react'; +import { AiFillHeart, AiOutlineComment, AiOutlineUpload } from 'react-icons/ai'; +import { BiDotsHorizontalRounded } from 'react-icons/bi'; +import { GrBookmark } from 'react-icons/gr'; +import './Feeds.scss'; +import Comments from './Comment/Comments'; + +export default function Feeds({ userId, profileImg, img, comments }) { + const [commentVal, setCommentVal] = useState(comments); + let addedCommentVal = [...commentVal]; + const [currInputVal, setCurrInputVal] = useState(''); + + const handleInput = e => { + const { value } = e.target; + if (e.keyCode === 13) uploadComment(); + setCurrInputVal(value); + }; + + const uploadComment = e => { + e.preventDefault(); + if (!currInputVal) return; + addedCommentVal.push({ + id: addedCommentVal.length + 1, + userId: 'userid', + value: currInputVal, + time: '๋ฐฉ๊ธˆ์ „', + }); + setCommentVal(addedCommentVal); + setCurrInputVal(''); + }; + + const handleDelete = e => { + const { id } = e.target.parentNode.parentNode; + addedCommentVal = addedCommentVal.filter(el => el.id !== Number(id)); + setCommentVal(addedCommentVal); + }; + + return ( + <div className="feeds"> + <article> + <div className="top_menu"> + <span> + <img src={profileImg} alt="ํ”„๋กœํ•„" /> + {userId} + </span> + <span> + <BiDotsHorizontalRounded /> + </span> + </div> + <img src={img} alt="๋ฌดํ™”๊ณผ" /> + <div className="bottom_menu"> + <span> + <AiFillHeart className="" /> + </span> + <span> + <AiOutlineComment className="" /> + </span> + <span> + <AiOutlineUpload className="" /> + </span> + <span> + <GrBookmark className="" /> + </span> + </div> + <div className="comments"> + <span>4 Likes</span> + <Comments commentArr={commentVal} handleDelete={handleDelete} /> + </div> + <form className="add_comments"> + <input + type="text" + placeholder="๋Œ“๊ธ€ ๋‹ฌ๊ธฐ..." + className="input_upload" + onChange={handleInput} + value={currInputVal} + /> + <button + className={currInputVal ? 'activated' : ''} + onClick={uploadComment} + > + ๊ฒŒ์‹œ + </button> + </form> + </article> + </div> + ); +}
Unknown
๊ต‰์žฅํžˆ ์ž˜ ์งœ์‹  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!! ๐Ÿ‘ ๊ทธ๋Ÿฐ๋ฐ ์ˆœ์„œ๊ฐ€ ์กฐ๊ธˆ ์• ๋งคํ•œ ๊ฒƒ ๊ฐ™์•„์š”. 17)์—์„œ uploadComment ํ˜ธ์ถœ์„ ํ•˜๊ณ  31)์—์„œ currInputVal( " " ) -> 18 ) ์—์„œ currInputVal( e.target.value ) ์ˆœ์œผ๋กœ ์ง„ํ–‰์ด ๋œ๋‹ค๋ฉด ๋Œ“๊ธ€์„ ์ถ”๊ฐ€ํ•˜๋”๋ผ๋„ input์€ ๋น„์›Œ์ง€์ง€ ์•Š์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,101 @@ +@use '../../../../styles/mixin.scss' as mixin; +@use '../../../../styles/color.scss' as clr; + +.feeds { + position: relative; + top: 77px; + width: 60%; + margin-bottom: 80px; + background: #fff; + + .top_menu { + @include mixin.flex($justify: space-between, $align: center); + height: 82px; + + span { + @include mixin.flex($align: center); + margin-left: 20px; + font-weight: bold; + + &:last-child { + margin-right: 22px; + color: #2a2a2a; + font-size: 35px; + } + + img { + width: 42px; + height: 42px; + border-radius: 50%; + margin-right: 20px; + } + } + } + + article { + img { + width: 100%; + height: 818px; + } + + .bottom_menu { + @include mixin.flex($align: center); + position: relative; + height: 62px; + + span > svg { + margin: 0 10px; + font-size: 32px; + color: #414141; + } + + span:last-child > svg { + position: absolute; + top: 15px; + right: 0; + } + + span:first-child > svg > path { + color: #eb4b59; + } + } + } + + .comments { + display: flex; + flex-direction: column; + + span { + padding-left: 10px; + } + } + + .add_comments { + position: absolute; + @include mixin.flex($justify: space-between, $align: center); + bottom: -62px; + width: 100%; + height: 62px; + border-top: 1px solid clr.$clr-border; + font-size: 14px; + + input { + width: 90%; + height: 50%; + margin-left: 15px; + border: none; + } + + button { + margin-right: 15px; + border: none; + color: clr.$clr-primary; + opacity: 0.5; + background: #fff; + + &.activated { + opacity: 1; + } + } + } +}
Unknown
Feeds.jsx์—์„œ .feeds์˜ ๋ฐ”๋กœ ์ž์‹์š”์†Œ๊ฐ€ article์ด๋ผ article์„ .feeds ๋ฐ”๋กœ ๋‹ค์Œ์— ์จ์ฃผ๋Š” ๊ฒŒ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  height์š”์†Œ๋Š” ์ž์‹์š”์†Œ๋“ค์˜ ๋†’์ด์— ๋”ฐ๋ผ ๊ฒฐ์ •๋˜๋‹ˆ๊น height: 100%๋ฅผ ์ฃผ์–ด๋„ feeds์˜ ๋†’์ด๊ฐ€ ๋ณ€ํ•˜์ง€๋Š” ์•Š์„ ๊ฒƒ ๊ฐ™๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“œ๋Š”๋ฐ ํ˜น์‹œ ์„ค์ •ํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ์œผ์‹ ๊ฐ€์š”?
@@ -1,5 +1,98 @@ import React from 'react'; +import { useState, useEffect } from 'react'; +import { useNavigate } from 'react-router-dom'; +import './Login.scss'; -export default function Login() { - return <div>Hello, Hyeonze!</div>; -} +const Login = () => { + const [idInput, setIdInput] = useState(''); + const [pwInput, setPwInput] = useState(''); + const [isValidatedUser, setIsValidatedUser] = useState(false); + + const navigate = useNavigate(); + const changeIdInput = e => { + const { value } = e.target; + setIdInput(value); + }; + + const changePwInput = e => { + const { value } = e.target; + setPwInput(value); + }; + + useEffect(() => { + setIsValidatedUser(idInput.indexOf('@') !== -1 && pwInput.length > 4); + }, [idInput, pwInput]); + + // ๋ฉ”์ธ์œผ๋กœ ์ด๋™ํ•  ๋•Œ ๋กœ์ง + const goToMain = () => { + navigate('/main-hyeonze'); + }; + + // ํšŒ์›๊ฐ€์ž…์‹œ ์‚ฌ์šฉํ•  ๋กœ์ง + // const signup = () => { + // fetch('http://10.58.4.22:8000/users/signup', { + // method: 'POST', + // body: JSON.stringify({ + // email: idInput, + // password: pwInput, + // }), + // }) + // .then(response => response.json()) + // .then(result => { + // //console.log('๊ฒฐ๊ณผ: ', result.message) + // if (result.message === 'EMAIL_ALREADY_EXISTS') { + // console.log('Error : Duplicated'); + // } + // }); + // }; + + // ๋กœ๊ทธ์ธ์‹œ ์‚ฌ์šฉํ•  ๋กœ์ง + // const login = () => { + // fetch('http://10.58.4.22:8000/users/login', { + // method: 'POST', + // body: JSON.stringify({ + // email: idInput, + // password: pwInput, + // }), + // }) + // .then(response => response.json()) + // .then(result => { + // //console.log('๊ฒฐ๊ณผ: ', result.message) + // if (result.message === 'SUCCESS') { + // console.log('login SUCCESS'); + // } + // }); + // }; + + return ( + <div className="login"> + <div id="wrapper"> + <h1>westagram</h1> + <form className="login_form"> + <input + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + className="username" + onChange={changeIdInput} + /> + <input + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + className="userpassword" + onChange={changePwInput} + /> + <input + className={isValidatedUser ? 'activated' : ''} + disabled={!isValidatedUser} + type="button" + value="๋กœ๊ทธ์ธ" + onClick={goToMain} + /> + </form> + <p>๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</p> + </div> + </div> + ); +}; + +export default Login;
Unknown
์ด ๋‘ ์กฐ๊ฑด์„ &&๋กœ ๊ฑธ๋ฉด state๋ฅผ ํ•˜๋‚˜๋งŒ ์‚ฌ์šฉํ•˜๊ณ  validation์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ์ง€ ์•Š์„๊นŒ์š”? => ๋งž๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์ˆ˜์ • ์ „ ์ฝ”๋“œ์—์„œ ์œ ํšจ์„ฑ๊ฒ€์‚ฌ๋ฅผ changeIdInput, changePwInput ๋‚ด์—์„œ ๊ฐ๊ฐ ํ•ด์คฌ์—ˆ๋Š”๋ฐ ํ˜ธํ™˜์„ฑ ๊ฒ€์‚ฌ์— ๋”œ๋ ˆ์ด๊ฐ€ ์ƒ๊ฒจ์„œ useEffect๋ฅผ ์‚ฌ์šฉํ•˜๋Š”๊ฒŒ ํ•ด๊ฒฐ์ฑ…์ด๋ผ ์ƒ๊ฐํ–ˆ์Šต๋‹ˆ๋‹ค. ์ด ๊ณผ์ •์—์„œ changeIdInput, changePwInput ๋‚ด๋ถ€์˜ ์‚ผํ•ญ์—ฐ์‚ฐ์ž๋“ค์„ useEffect ๋‚ด๋ถ€๋กœ ์ž˜๋ผ๋‚ด์–ด ์˜ค๊ฒŒ ๋˜๋ฉด์„œ ๋กœ์ง์ด ๊ธธ์–ด์ง„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -1,5 +1,98 @@ import React from 'react'; +import { useState, useEffect } from 'react'; +import { useNavigate } from 'react-router-dom'; +import './Login.scss'; -export default function Login() { - return <div>Hello, Hyeonze!</div>; -} +const Login = () => { + const [idInput, setIdInput] = useState(''); + const [pwInput, setPwInput] = useState(''); + const [isValidatedUser, setIsValidatedUser] = useState(false); + + const navigate = useNavigate(); + const changeIdInput = e => { + const { value } = e.target; + setIdInput(value); + }; + + const changePwInput = e => { + const { value } = e.target; + setPwInput(value); + }; + + useEffect(() => { + setIsValidatedUser(idInput.indexOf('@') !== -1 && pwInput.length > 4); + }, [idInput, pwInput]); + + // ๋ฉ”์ธ์œผ๋กœ ์ด๋™ํ•  ๋•Œ ๋กœ์ง + const goToMain = () => { + navigate('/main-hyeonze'); + }; + + // ํšŒ์›๊ฐ€์ž…์‹œ ์‚ฌ์šฉํ•  ๋กœ์ง + // const signup = () => { + // fetch('http://10.58.4.22:8000/users/signup', { + // method: 'POST', + // body: JSON.stringify({ + // email: idInput, + // password: pwInput, + // }), + // }) + // .then(response => response.json()) + // .then(result => { + // //console.log('๊ฒฐ๊ณผ: ', result.message) + // if (result.message === 'EMAIL_ALREADY_EXISTS') { + // console.log('Error : Duplicated'); + // } + // }); + // }; + + // ๋กœ๊ทธ์ธ์‹œ ์‚ฌ์šฉํ•  ๋กœ์ง + // const login = () => { + // fetch('http://10.58.4.22:8000/users/login', { + // method: 'POST', + // body: JSON.stringify({ + // email: idInput, + // password: pwInput, + // }), + // }) + // .then(response => response.json()) + // .then(result => { + // //console.log('๊ฒฐ๊ณผ: ', result.message) + // if (result.message === 'SUCCESS') { + // console.log('login SUCCESS'); + // } + // }); + // }; + + return ( + <div className="login"> + <div id="wrapper"> + <h1>westagram</h1> + <form className="login_form"> + <input + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + className="username" + onChange={changeIdInput} + /> + <input + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + className="userpassword" + onChange={changePwInput} + /> + <input + className={isValidatedUser ? 'activated' : ''} + disabled={!isValidatedUser} + type="button" + value="๋กœ๊ทธ์ธ" + onClick={goToMain} + /> + </form> + <p>๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</p> + </div> + </div> + ); +}; + +export default Login;
Unknown
[๊ณต์‹๋ฌธ์„œ React๋กœ ์‚ฌ๊ณ ํ•˜๊ธฐ](https://ko.reactjs.org/docs/thinking-in-react.html#step-3-identify-the-minimal-but-complete-representation-of-ui-state) ๋ฅผ ๋ณด์‹œ๋ฉด ์–ด๋–ค ๊ฐ’๋“ค์ด state๊ฐ€ ๋˜์–ด์•ผํ•˜๋Š”์ง€์— ๋Œ€ํ•ด ์ ํ˜€์žˆ์Šต๋‹ˆ๋‹ค. ๊ฐ๊ฐ ์‚ดํŽด๋ณด๊ณ  ํ•ด๋‹น ๋ฐ์ดํ„ฐ๋Š” state๋กœ ์ ์ ˆํ•œ์ง€ ๋Œ“๊ธ€๋กœ ๋‚จ๊ฒจ์ฃผ์„ธ์š”. ๊ฐ ๋ฐ์ดํ„ฐ์— ๋Œ€ํ•ด ์•„๋ž˜์˜ ์„ธ ๊ฐ€์ง€ ์งˆ๋ฌธ์„ ํ†ตํ•ด ๊ฒฐ์ •ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค > 1. ๋ถ€๋ชจ๋กœ๋ถ€ํ„ฐ props๋ฅผ ํ†ตํ•ด ์ „๋‹ฌ๋ฉ๋‹ˆ๊นŒ? ๊ทธ๋Ÿฌ๋ฉด ํ™•์‹คํžˆ state๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค. > > 2. ์‹œ๊ฐ„์ด ์ง€๋‚˜๋„ ๋ณ€ํ•˜์ง€ ์•Š๋‚˜์š”? ๊ทธ๋Ÿฌ๋ฉด ํ™•์‹คํžˆ state๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค. > > 3. ์ปดํฌ๋„ŒํŠธ ์•ˆ์˜ ๋‹ค๋ฅธ state๋‚˜ props๋ฅผ ๊ฐ€์ง€๊ณ  ๊ณ„์‚ฐ ๊ฐ€๋Šฅํ•œ๊ฐ€์š”? ๊ทธ๋ ‡๋‹ค๋ฉด state๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค. >
@@ -1,5 +1,98 @@ import React from 'react'; +import { useState, useEffect } from 'react'; +import { useNavigate } from 'react-router-dom'; +import './Login.scss'; -export default function Login() { - return <div>Hello, Hyeonze!</div>; -} +const Login = () => { + const [idInput, setIdInput] = useState(''); + const [pwInput, setPwInput] = useState(''); + const [isValidatedUser, setIsValidatedUser] = useState(false); + + const navigate = useNavigate(); + const changeIdInput = e => { + const { value } = e.target; + setIdInput(value); + }; + + const changePwInput = e => { + const { value } = e.target; + setPwInput(value); + }; + + useEffect(() => { + setIsValidatedUser(idInput.indexOf('@') !== -1 && pwInput.length > 4); + }, [idInput, pwInput]); + + // ๋ฉ”์ธ์œผ๋กœ ์ด๋™ํ•  ๋•Œ ๋กœ์ง + const goToMain = () => { + navigate('/main-hyeonze'); + }; + + // ํšŒ์›๊ฐ€์ž…์‹œ ์‚ฌ์šฉํ•  ๋กœ์ง + // const signup = () => { + // fetch('http://10.58.4.22:8000/users/signup', { + // method: 'POST', + // body: JSON.stringify({ + // email: idInput, + // password: pwInput, + // }), + // }) + // .then(response => response.json()) + // .then(result => { + // //console.log('๊ฒฐ๊ณผ: ', result.message) + // if (result.message === 'EMAIL_ALREADY_EXISTS') { + // console.log('Error : Duplicated'); + // } + // }); + // }; + + // ๋กœ๊ทธ์ธ์‹œ ์‚ฌ์šฉํ•  ๋กœ์ง + // const login = () => { + // fetch('http://10.58.4.22:8000/users/login', { + // method: 'POST', + // body: JSON.stringify({ + // email: idInput, + // password: pwInput, + // }), + // }) + // .then(response => response.json()) + // .then(result => { + // //console.log('๊ฒฐ๊ณผ: ', result.message) + // if (result.message === 'SUCCESS') { + // console.log('login SUCCESS'); + // } + // }); + // }; + + return ( + <div className="login"> + <div id="wrapper"> + <h1>westagram</h1> + <form className="login_form"> + <input + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + className="username" + onChange={changeIdInput} + /> + <input + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + className="userpassword" + onChange={changePwInput} + /> + <input + className={isValidatedUser ? 'activated' : ''} + disabled={!isValidatedUser} + type="button" + value="๋กœ๊ทธ์ธ" + onClick={goToMain} + /> + </form> + <p>๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</p> + </div> + </div> + ); +}; + +export default Login;
Unknown
๋ผ์ด๋ธŒ๋ฆฌ๋ทฐ ๋•Œ ๋ง์”€๋“œ๋ฆฐ ๊ฒƒ์ฒ˜๋Ÿผ ์กฐ๊ฑด์˜ falsy, truthyํ•œ ๊ฐ’์„ ์ด์šฉํ•ด ๋ฆฌํŒฉํ† ๋ง ํ•ด์ฃผ์„ธ์š”! :) ๋˜๋Š” state๋ฅผ ์ค„์ผ ๊ฒฝ์šฐ ๋ถˆํ•„์š”ํ•  ์ˆ˜๋„ ์žˆ๊ฒ ๋„ค์š”
@@ -0,0 +1,66 @@ +@use '../../../styles/mixin.scss' as mixin; +@use '../../../styles/color.scss' as clr; + +body { + background: clr.$bg-login; + + .login { + position: relative; + top: -80px; + + #wrapper { + @include mixin.flex($align: center); + position: relative; + flex-direction: column; + width: 700px; + height: 761px; + border: 1px solid clr.$clr-border; + + h1 { + margin-top: 90px; + margin-bottom: 130px; + font-size: 81px; + font-family: 'Lobster', cursive; + } + + .login_form { + input { + display: block; + width: 536px; + height: 76px; + margin-bottom: 12px; + padding-left: 10px; + background: #fafafa; + border: 1px solid clr.$clr-border; + border-radius: 3px; + font-size: 16px; + } + + input[type='button'] { + display: flex; + align-items: center; + justify-content: center; + width: 536px; + height: 60px; + margin-top: 16px; + background-color: clr.$clr-primary; + opacity: 0.5; + border: none; + border-radius: 4px; + font-size: 16px; + color: #fff; + + &.activated { + opacity: 1; + } + } + } + + p { + position: absolute; + bottom: 20px; + color: #043667; + } + } + } +}
Unknown
์œ„ ์ฝ”๋“œ๋Š” ์–ด๋””์— ์ž‘์„ฑ๋˜๋ฉด ์ข‹์„๊นŒ์š”?
@@ -0,0 +1,43 @@ +span.comment { + padding-left: 10px; + + small { + color: #a3a3a3; + } + + &:first-child { + padding: 10px; + font-weight: bold; + } + + svg { + &.delete { + display: none; + cursor: pointer; + } + + &.hearts { + color: #a3a3a3; + position: absolute; + right: 20px; + transition: color 1s; + cursor: pointer; + + path { + color: #a3a3a3; + } + } + + &.liked { + path { + color: #f00; + } + } + } + + &:hover svg { + &.delete { + display: inline-block; + } + } +}
Unknown
์ž์ฃผ ์‚ฌ์šฉ์ด ๋˜๋Š” ์ปฌ๋Ÿฌ๊ฐ’์ด๋„ค์š”! ์ด๋Ÿฐ ๊ฒฝ์šฐ sass variables ๊ธฐ๋Šฅ์„ ์ด์šฉํ•˜๋Š”๊ฒƒ์€ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,87 @@ +import React, { useState } from 'react'; +import { AiFillHeart, AiOutlineComment, AiOutlineUpload } from 'react-icons/ai'; +import { BiDotsHorizontalRounded } from 'react-icons/bi'; +import { GrBookmark } from 'react-icons/gr'; +import './Feeds.scss'; +import Comments from './Comment/Comments'; + +export default function Feeds({ userId, profileImg, img, comments }) { + const [commentVal, setCommentVal] = useState(comments); + let addedCommentVal = [...commentVal]; + const [currInputVal, setCurrInputVal] = useState(''); + + const handleInput = e => { + const { value } = e.target; + if (e.keyCode === 13) uploadComment(); + setCurrInputVal(value); + }; + + const uploadComment = e => { + e.preventDefault(); + if (!currInputVal) return; + addedCommentVal.push({ + id: addedCommentVal.length + 1, + userId: 'userid', + value: currInputVal, + time: '๋ฐฉ๊ธˆ์ „', + }); + setCommentVal(addedCommentVal); + setCurrInputVal(''); + }; + + const handleDelete = e => { + const { id } = e.target.parentNode.parentNode; + addedCommentVal = addedCommentVal.filter(el => el.id !== Number(id)); + setCommentVal(addedCommentVal); + }; + + return ( + <div className="feeds"> + <article> + <div className="top_menu"> + <span> + <img src={profileImg} alt="ํ”„๋กœํ•„" /> + {userId} + </span> + <span> + <BiDotsHorizontalRounded /> + </span> + </div> + <img src={img} alt="๋ฌดํ™”๊ณผ" /> + <div className="bottom_menu"> + <span> + <AiFillHeart className="" /> + </span> + <span> + <AiOutlineComment className="" /> + </span> + <span> + <AiOutlineUpload className="" /> + </span> + <span> + <GrBookmark className="" /> + </span> + </div> + <div className="comments"> + <span>4 Likes</span> + <Comments commentArr={commentVal} handleDelete={handleDelete} /> + </div> + <form className="add_comments"> + <input + type="text" + placeholder="๋Œ“๊ธ€ ๋‹ฌ๊ธฐ..." + className="input_upload" + onChange={handleInput} + value={currInputVal} + /> + <button + className={currInputVal ? 'activated' : ''} + onClick={uploadComment} + > + ๊ฒŒ์‹œ + </button> + </form> + </article> + </div> + ); +}
Unknown
.ํ•ด๋‹น ๋ถ€๋ถ„๋„ ์ข€ ๋” ๋ฐ˜๋ณต๋˜๋Š” ๋‹จ์–ด๋ฅผ ์ค„์ผ ์ˆ˜ ์—†์„์ง€ ๊ณ ๋ฏผํ•ด๋ด…์‹œ๋‹ค. ๋”๋ถˆ์–ด ๋ถˆํ•„์š”ํ•œ state๊ฐ’๋„ ๋ณด์ด๋„ค์š”! ์œ„ ๋ฆฌ๋ทฐ๋ฅผ ์ฐธ๊ณ ํ•ด ์ˆ˜์ •ํ•ด์ฃผ์„ธ์š”!