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 | 
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๊ฐ๋ ๋ณด์ด๋ค์! ์ ๋ฆฌ๋ทฐ๋ฅผ ์ฐธ๊ณ ํด ์์ ํด์ฃผ์ธ์! |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.