Skip to content

Commit

Permalink
Merge pull request #128 from TRIP-Side-Project/dev
Browse files Browse the repository at this point in the history
pr for merge
  • Loading branch information
kwondongwook authored Dec 26, 2023
2 parents 72958b9 + 6f67d15 commit a2c8871
Show file tree
Hide file tree
Showing 8 changed files with 280 additions and 9 deletions.
42 changes: 42 additions & 0 deletions src/main/java/com/api/trip/common/init/InitData.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package com.api.trip.common.init;

import com.api.trip.common.naverapi.NaverApiService;
import com.api.trip.common.naverapi.NaverClient;
import com.api.trip.common.naverapi.dto.ShoppingItem;
import com.api.trip.common.naverapi.dto.ShoppingRequest;
import com.api.trip.common.naverapi.dto.ShoppingResponse;
import com.api.trip.domain.item.controller.dto.CreateItemRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@RequiredArgsConstructor
public class InitData implements ApplicationRunner {

private final NaverClient naverClient;
private final NaverApiService naverApiService;

@Override
public void run(ApplicationArguments args) throws Exception {

/*
ShoppingRequest request = ShoppingRequest.builder()
.start(1)
.display(100).build();
ShoppingResponse searchResponse = naverClient.search(request);
List<ShoppingItem> shoppingItems = naverApiService.doFilterCategory(searchResponse.getItems());
List<CreateItemRequest> createItemRequests = naverApiService.toCreateItemRequest(shoppingItems);
for(CreateItemRequest createItemRequest :createItemRequests)
System.out.println(createItemRequest.toString());
*/

}
}
48 changes: 48 additions & 0 deletions src/main/java/com/api/trip/common/naverapi/NaverApiService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package com.api.trip.common.naverapi;


import com.api.trip.common.naverapi.dto.ShoppingItem;
import com.api.trip.domain.item.controller.dto.CreateItemRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class NaverApiService {

private final List<String> tagList = Arrays.asList("부산", "제주", "서울", "크루즈", "일출", "해수욕장");

public List<ShoppingItem> doFilterCategory(List<ShoppingItem> items){
List<ShoppingItem> filteredItems = new ArrayList<>();
for (ShoppingItem item: items)
{
if(
item.getCategory1().equals("국내패키지/기타") ||
item.getCategory2().equals("국내패키지/기타") ||
item.getCategory3().equals("국내패키지/기타") ||
item.getCategory4().equals("국내패키지/기타")
)
filteredItems.add(item);
}
return filteredItems;
}

public List<CreateItemRequest> toCreateItemRequest(List<ShoppingItem> items){
List<CreateItemRequest> createItemRequests = new ArrayList<>();


for(ShoppingItem item : items){

List<String> tagsNames = extractTagNames(item.getTitle());
createItemRequests.add(CreateItemRequest.of(item, tagsNames));

}
return createItemRequests;
}

public List<String> extractTagNames(String title){
return tagList.stream().filter(tag -> title.contains(tag)).toList();
}
}
47 changes: 47 additions & 0 deletions src/main/java/com/api/trip/common/naverapi/NaverClient.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package com.api.trip.common.naverapi;

import com.api.trip.common.naverapi.dto.ShoppingRequest;
import com.api.trip.common.naverapi.dto.ShoppingResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;

@Component //빈으로 등록
public class NaverClient {
@Value("${custom.naver.url}")
private String naverUrl;
@Value("${custom.naver.clientId}")
private String clientId;
@Value("${custom.naver.clientSecret}")
private String clientSecret;

public ShoppingResponse search(ShoppingRequest request) {
URI uri = UriComponentsBuilder.fromUriString(naverUrl)
.queryParams(request.map())
.build()
.encode()
.toUri();

HttpHeaders headers = new HttpHeaders();
headers.set("X-Naver-Client-Id", clientId);
headers.set("X-Naver-Client-Secret", clientSecret);

HttpEntity httpEntity = new HttpEntity<>(headers);

ResponseEntity<ShoppingResponse> entity = new RestTemplate().exchange(
uri,
HttpMethod.GET,
httpEntity,
ShoppingResponse.class
);

return entity.getBody();
}
}
24 changes: 24 additions & 0 deletions src/main/java/com/api/trip/common/naverapi/dto/ShoppingItem.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.api.trip.common.naverapi.dto;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class ShoppingItem {
private Long productId;
private String title; //상품이름
private String link; //상품 url
private String image; //상품 이미지 url
private Integer lprice; //최저가
private Integer hprice; //최고가
private String mallName; //상품을 판매하는 쇼핑몰
private String maker; //제조사
private String brand; //브랜드
private String category1;
private String category2;
private String category3;
private String category4;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.api.trip.common.naverapi.dto;

import lombok.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

@Getter
@NoArgsConstructor //기본 생성자 만들기
public class ShoppingRequest {
private String query; //검색어
private String sort;
private Integer display; //검색결과 갯수는 1개만
private Integer start;

@Builder
public ShoppingRequest(Integer display, Integer start) {
this.query = "국내패키지";
this.sort = "date";
this.display = display;
this.start = start;
}

public MultiValueMap map() { //파라미터를 넘기기 위한 맵
LinkedMultiValueMap<String, String > map = new LinkedMultiValueMap();
map.add("query", query);
map.add("display", String.valueOf(display));
map.add("sort", sort);
map.add("start", String.valueOf(start));
return map;
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.api.trip.common.naverapi.dto;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;
import java.util.List;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class ShoppingResponse {
private Date lastBuildDate; //검색결과를 생성한 시간
private String total; //총 검색 결과
private List<ShoppingItem> items; //아이템을 받을 리스트


}
43 changes: 36 additions & 7 deletions src/main/java/com/api/trip/common/security/jwt/JwtTokenFilter.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package com.api.trip.common.security.jwt;

import com.api.trip.common.exception.CustomException;
import com.api.trip.common.exception.ErrorCode;
import com.api.trip.common.exception.ErrorResponse;
import com.api.trip.common.security.util.JwtTokenUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
Expand All @@ -22,23 +26,48 @@ public class JwtTokenFilter extends OncePerRequestFilter {

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
ObjectMapper objectMapper = new ObjectMapper();

try {

String accessToken = JwtTokenUtils.extractBearerToken(request.getHeader("accessToken"));
String accessToken = JwtTokenUtils.extractBearerToken(request.getHeader("accessToken"));


if (!request.getRequestURI().equals("/api/members/rotate") && accessToken != null) { // 토큰 재발급의 요청이 아니면서 accessToken이 존재할 때

if (!request.getRequestURI().equals("/api/members/rotate") && accessToken != null) { // 토큰 재발급의 요청이 아니면서 accessToken이 존재할 때
// 토큰이 유효한 경우 and 로그인 상태
Authentication authentication = jwtTokenProvider.getAuthenticationByAccessToken(accessToken);
jwtTokenProvider.checkLogin(authentication.getName());

// 토큰이 유효한 경우 and 로그인 상태
Authentication authentication = jwtTokenProvider.getAuthenticationByAccessToken(accessToken);
jwtTokenProvider.checkLogin(authentication.getName());
SecurityContextHolder.getContext().setAuthentication(authentication);

SecurityContextHolder.getContext().setAuthentication(authentication);
}

filterChain.doFilter(request, response);
}catch (CustomException e){
ErrorCode errorCode = e.getErrorCode();

response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
response.setStatus(errorCode.getStatus().value());
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods","*");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, accessToken, refreshToken");
if("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
}
else{
log.error(errorCode.getMessage());
response.getWriter().write(
objectMapper.writeValueAsString(new ErrorResponse(errorCode.getMessage()))
);
}

}

filterChain.doFilter(request, response);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
package com.api.trip.domain.item.controller.dto;

import com.api.trip.common.naverapi.dto.ShoppingItem;
import com.api.trip.domain.item.model.Item;
import com.api.trip.domain.member.model.Member;
import jakarta.persistence.Column;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.Builder;
import lombok.Getter;
import lombok.ToString;

import java.util.List;

@Getter
@ToString
public class CreateItemRequest {

@NotBlank(message = "상품 id는 필수 입력값 입니다.")
Expand All @@ -26,16 +30,41 @@ public class CreateItemRequest {
private String buyUrl;

@Min(value=0, message="상품의 최고가는 0원 이상입니다.")
private long maxPrice;
private Integer maxPrice;

@Min(value=0, message="상품의 최저가는 0원 이상입니다.")
private long minPrice;
private Integer minPrice;

@NotBlank(message = "상품 id는 필수 입력값 입니다.")
private String imageUrl;

private List<String> tagNames;

@Builder
private CreateItemRequest(Long productId, String title, String shopName, String buyUrl, Integer maxPrice, Integer minPrice, String imageUrl, List<String> tagNames) {
this.productId = productId;
this.title = title;
this.shopName = shopName;
this.buyUrl = buyUrl;
this.maxPrice = maxPrice;
this.minPrice = minPrice;
this.imageUrl = imageUrl;
this.tagNames = tagNames;
}

public static CreateItemRequest of(ShoppingItem shoppingItem, List<String> tagNames){
return CreateItemRequest.builder()
.productId(shoppingItem.getProductId())
.title(shoppingItem.getTitle())
.shopName(shoppingItem.getMallName())
.buyUrl(shoppingItem.getLink())
.maxPrice(shoppingItem.getHprice())
.minPrice(shoppingItem.getLprice())
.imageUrl(shoppingItem.getImage())
.tagNames(tagNames)
.build();
}

public Item toEntity(){
return Item.builder()
.productId(productId)
Expand Down

0 comments on commit a2c8871

Please sign in to comment.