Skip to content

Commit

Permalink
[BE] location Array로 받을수 있도록 수정 (#366)
Browse files Browse the repository at this point in the history
  • Loading branch information
lvalentine6 committed Aug 2, 2023
2 parents 755f864 + 29bba9d commit 5fc7aa0
Show file tree
Hide file tree
Showing 8 changed files with 139 additions and 42 deletions.
2 changes: 2 additions & 0 deletions be/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ dependencies {
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.projectlombok:lombok:1.18.26'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'org.springframework:spring-test:5.3.10'
implementation 'commons-io:commons-io:2.8.0'
implementation 'com.amazonaws:aws-java-sdk-s3:1.12.464'
implementation 'org.yaml:snakeyaml:1.29'
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import codesquad.secondhand.dto.ResponseListDto;
import codesquad.secondhand.dto.location.LocationDto;
import codesquad.secondhand.dto.location.LocationListDto;
import codesquad.secondhand.dto.location.LocationIdDto;
import codesquad.secondhand.entity.Location;
import codesquad.secondhand.service.LocationService;
import lombok.RequiredArgsConstructor;
Expand All @@ -33,8 +34,8 @@ public ResponseListDto<LocationDto> showLocations() {
}

@PostMapping
public ResponseListDto<Location> searchLocationId(LocationListDto locationListDto) {
List<Location> list = locationService.findLocationId(locationListDto);
public ResponseListDto<Location> searchLocationId(@RequestBody List<LocationIdDto> locationIdDtoList) {
List<Location> list = locationService.findLocationId(locationIdDtoList);
return ResponseListDto.of(RESPONSE_SUCCESS, list);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
package codesquad.secondhand.dto.location;

import java.util.List;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@AllArgsConstructor
public class LocationListDto {
@NoArgsConstructor
public class LocationIdDto {

private List<String> locationString;
private String locationString;

@Override
public String toString() {
Expand Down
14 changes: 14 additions & 0 deletions be/src/main/java/codesquad/secondhand/entity/Member.java
Original file line number Diff line number Diff line change
Expand Up @@ -85,4 +85,18 @@ public void updateLocations(Location newMainLocation, Location newSubLocation) {
this.mainLocation = newMainLocation;
this.subLocation = newSubLocation;
}

@Override
public String toString() {
return "Member{" +
"memberIdx=" + memberIdx +
", loginId='" + loginId + '\'' +
", password='" + password + '\'' +
", imagePath='" + imagePath + '\'' +
", imageUrl='" + imageUrl + '\'' +
", mainLocation=" + mainLocation +
", subLocation=" + subLocation +
", oauthId='" + oauthId + '\'' +
'}';
}
}
46 changes: 46 additions & 0 deletions be/src/main/java/codesquad/secondhand/service/ImageService.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,12 @@
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

Expand Down Expand Up @@ -46,6 +49,9 @@ public String upload(MultipartFile multipartFile, String memberId) {

String fileName = memberProfileFileNameConvert(originFileName, memberId);

long fileSize = multipartFile.getSize();
objectMetadata.setContentLength(fileSize);

objectMetadata.setContentType(multipartFile.getContentType());

try (InputStream inputStream = multipartFile.getInputStream()) {
Expand Down Expand Up @@ -115,6 +121,37 @@ public List<String> upload(Long imageIdx, ItemDetailDto itemDetailDto) {
return itemUrlList;
}

public List<String> upload(Long imageIdx, List<MultipartFile> multipartFileList) {
List<String> itemUrlList = new ArrayList<>();
Random random = new Random();
int cnt = 1;

for (int i = 0; i < 2; i++) {
int rand = random.nextInt(3) + 1;
ObjectMetadata objectMetadata = new ObjectMetadata();
String originFileName = multipartFileList.get(rand).getOriginalFilename();

if (originFileName == null) {
originFileName = UUID.randomUUID().toString();
}

String fileName = itemFileNameConvert(originFileName, imageIdx, cnt);

objectMetadata.setContentType(multipartFileList.get(rand).getContentType());
objectMetadata.setContentLength(multipartFileList.get(rand).getSize());

try (InputStream inputStream = multipartFileList.get(rand).getInputStream()) {
amazonS3.putObject(new PutObjectRequest(bucketName, fileName, inputStream, objectMetadata)
.withCannedAcl(CannedAccessControlList.PublicRead));
} catch (IOException e) {
throw new FileUploadFailedException(ImageErrorCode.FileUploadFailedException);
}
itemUrlList.add(fileName + "@" + amazonS3.getUrl(bucketName, fileName).toString());
cnt++;
}
return itemUrlList;
}

private String memberProfileFileNameConvert(String originalFileName, String memberId, String fileExtension) {
StringBuilder sb = new StringBuilder();
int lastDot = originalFileName.lastIndexOf(FILE_EXTENSION_DOT);
Expand Down Expand Up @@ -172,4 +209,13 @@ private String itemFileNameConvert(String originalFileName, Long itemIdx, int cn
.append(fileName);
return sb.toString();
}

public static MultipartFile createMultipartFileFromPath(String imagePath) throws IOException {
FileSystemResource fileSystemResource = new FileSystemResource(imagePath);
return new MockMultipartFile(
fileSystemResource.getFilename(),
fileSystemResource.getFilename(),
null,
fileSystemResource.getInputStream());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import org.springframework.transaction.annotation.Transactional;

import codesquad.secondhand.dto.location.LocationDto;
import codesquad.secondhand.dto.location.LocationListDto;
import codesquad.secondhand.dto.location.LocationIdDto;
import codesquad.secondhand.entity.Location;
import codesquad.secondhand.repository.LocationRepository;
import lombok.RequiredArgsConstructor;
Expand All @@ -30,11 +30,11 @@ public List<LocationDto> showAllLocations() {
.collect(Collectors.toList());
}

public List<Location> findLocationId(LocationListDto locationListDto) {
public List<Location> findLocationId(List<LocationIdDto> locationIdDtoList) {
List<Location> list = new ArrayList<>();

for (String s : locationListDto.getLocationString()) {
String[] locationString = s.split(" ");
for (LocationIdDto l : locationIdDtoList) {
String[] locationString = l.getLocationString().split(" ");
Location location = locationRepository.findLocationByCityAndDistrictAndTown(locationString[0],
locationString[1], locationString[2]).orElseThrow();
list.add(location);
Expand Down
2 changes: 1 addition & 1 deletion be/src/main/resources/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ CREATE TABLE IF NOT EXISTS `second-hand`.`member`
`sub_location_idx` BIGINT(10) NULL,
`login_id` VARCHAR(45) NOT NULL,
`password` VARCHAR(45) NULL,
`image_path` VARCHAR(100) NULL,
`image_path` VARCHAR(500) NULL,
`image_url` VARCHAR(500) NULL,
`oauth_id` VARCHAR(45) NULL DEFAULT NULL,
PRIMARY KEY (`member_idx`),
Expand Down
94 changes: 64 additions & 30 deletions be/src/test/java/codesquad/secondhand/config/TestDummyData.java
Original file line number Diff line number Diff line change
@@ -1,18 +1,26 @@
package codesquad.secondhand.config;

import static codesquad.secondhand.service.ImageService.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.web.multipart.MultipartFile;

import com.github.javafaker.Faker;

import codesquad.secondhand.entity.Category;
import codesquad.secondhand.entity.Item;
import codesquad.secondhand.entity.ItemImage;
import codesquad.secondhand.entity.Location;
import codesquad.secondhand.entity.Member;
import codesquad.secondhand.repository.CategoryRepository;
import codesquad.secondhand.repository.ChatRoomRepository;
import codesquad.secondhand.repository.InterestRepository;
import codesquad.secondhand.repository.ItemImageRepository;
import codesquad.secondhand.repository.ItemRepository;
import codesquad.secondhand.repository.LocationRepository;
Expand All @@ -23,21 +31,17 @@
public class TestDummyData {

private final ItemRepository itemRepository;
private final ChatRoomRepository chatRoomRepository;
private final InterestRepository interestRepository;
private final CategoryRepository categoryRepository;
private final MemberRepository memberRepository;
private final LocationRepository locationRepository;
private final ItemImageRepository itemImageRepository;
private final ImageService imageService;

@Autowired
public TestDummyData(ItemRepository itemRepository, ChatRoomRepository chatRoomRepository,
InterestRepository interestRepository, CategoryRepository categoryRepository, MemberRepository memberRepository,
LocationRepository locationRepository, ItemImageRepository itemImageRepository, ImageService imageService) {
public TestDummyData(ItemRepository itemRepository,
CategoryRepository categoryRepository, MemberRepository memberRepository, LocationRepository locationRepository,
ItemImageRepository itemImageRepository, ImageService imageService) {
this.itemRepository = itemRepository;
this.chatRoomRepository = chatRoomRepository;
this.interestRepository = interestRepository;
this.categoryRepository = categoryRepository;
this.memberRepository = memberRepository;
this.locationRepository = locationRepository;
Expand All @@ -46,29 +50,59 @@ public TestDummyData(ItemRepository itemRepository, ChatRoomRepository chatRoomR
}

@Test
public void createDummyData() {
public void createDummyData() throws IOException {
Faker faker = new Faker(new Locale("ko"));

// 지역 정보 리스트
List<Location> locations = locationRepository.findAll();
System.out.println(locations);

// for (Location location : locations) {
// // 사용자 생성
// Member user = new User();
// user.setName(faker.name().fullName()); // 랜덤한 이름
// user.setLocation(location); // 지역 설정
// // ... 사용자의 다른 필드 설정
//
// // 상품 생성
// Item item = new Item();
// item.setName(faker.commerce().productName()); // 랜덤한 상품 이름
// item.setLocation(location); // 지역 설정
// // ... 상품의 다른 필드 설정
//
// // 저장소에 저장
// userRepository.save(user);
// itemRepository.save(item);
// }
List<Category> categories = categoryRepository.findAll();
List<MultipartFile> multipartFileList = new ArrayList<>();
MultipartFile multipartFileProfile = createMultipartFileFromPath("D:/A/BG/" + 0 + ".png");


for (int i = 1; i <= 4; i++) {
String filePath = "D:/A/BG/" + i + ".png";
MultipartFile file = createMultipartFileFromPath(filePath);
multipartFileList.add(file);
}

for (int i = 0; i < locations.size(); i++) {
String memberId = UUID.randomUUID().toString().substring(0, 10);
String password = faker.internet().password();
String[] profileUrl = imageService.upload(multipartFileProfile, memberId).split("@");
String imagePath = profileUrl[1];
String imageUrl = profileUrl[0];
Location mainLocation = locations.get(i);
Location subLocation = locations.get((i + 1) % locations.size());

Member member = new Member(memberId, password, imagePath, imageUrl, mainLocation, subLocation);
member.updateLocations(mainLocation, subLocation);

memberRepository.save(member);

for (int j = 0; j < 6; j++) {
Category randomCategory = categories.get(faker.random().nextInt(categories.size()));
String name = faker.commerce().productName();
String description = faker.lorem().sentence();
Integer price = faker.number().randomDigitNotZero() * 1000;
Integer view = faker.number().numberBetween(0, 100);
String status = "판매중";

Item item = new Item(member, randomCategory, member.getMainLocation(), null, name, description, price,
view, status);
itemRepository.save(item);

List<String> url = imageService.upload(item.getItemIdx(), multipartFileList);
for (int k = 0; k < url.size(); k++) {
String[] temp = url.get(k).split("@");
if (k == 0) {
ItemImage itemImage = itemImageRepository.save(new ItemImage(item, temp[1], temp[0]));
item.setItemImage(itemImage);
itemRepository.save(item);
continue;
}
itemImageRepository.save(new ItemImage(item, temp[1], temp[0]));
}
}
}
}
}

0 comments on commit 5fc7aa0

Please sign in to comment.