Skip to content

Commit

Permalink
Merge pull request #82 from TravelCompass-UMC/feature/20-naverApi
Browse files Browse the repository at this point in the history
[#20] 네이버 경로 api
  • Loading branch information
persi0815 authored Feb 13, 2024
2 parents 9aa29b8 + f0e0ee1 commit a2e26b9
Show file tree
Hide file tree
Showing 8 changed files with 137 additions and 12 deletions.
4 changes: 2 additions & 2 deletions src/main/java/com/travelcompass/api/LocalDataLoader.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ public void run(ApplicationArguments args) {
.star(4.2)
.roadNameAddress("서울특별시 성동구 뚝섬로 273")
.tel("02-460-2905")
.latitude(37.543072)
.longitude(127.041808)
.latitude(37.123451)
.longitude(128.123451)
.region(region)
.build());

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.travelcompass.api.feign.Naver;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@FeignClient(name = "naverDurationClient", url = "${naver.directions.api-url}")
public interface NaverDurationClient {

@GetMapping("/v1/driving")
ResponseEntity<String> getDuration(@RequestParam("start") String start,
@RequestParam("goal") String goal,
@RequestHeader("X-NCP-APIGW-API-KEY-ID") String clientId,
@RequestHeader("X-NCP-APIGW-API-KEY") String clientSecret);
}
/* 요청 예시
curl -X GET "https://naveropenapi.apigw.ntruss.com/map-direction/v1/driving?start=127.12345,37.12345&goal=128.12345,37.12345" \
-H "X-NCP-APIGW-API-KEY-ID: g4444lcndr" \
-H "X-NCP-APIGW-API-KEY: qXHf876pnArw9AQ36pfsfVmL0kqCB8ppEqj5A2Lm"
*/
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package com.travelcompass.api.feign.Naver;

import com.travelcompass.api.global.api_payload.ApiResponse;
import com.travelcompass.api.global.api_payload.SuccessCode;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

@Tag(name = "여행계획 경로", description = "경로(자가용) 관련 api 입니다. - 양지원")
@RequiredArgsConstructor
@RestController
public class NaverPathController {

private final NaverPathService naverPathService;

@Operation(summary = "여행계획 경로", description = "장소 id를 파라미터로 주면, 자가용 소요시간을 반환하는 메서드입니다.")
@ApiResponses({
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "PLAN_2031", description = "네이버 경로탐색이 완료되었습니다.(단위: 1/1000초)"),
})
@Parameters({
@Parameter(name = "start", description = "출발지의 location-id"),
@Parameter(name = "goal", description = "도착지의 location-id"),
})
@GetMapping("/getCarDuration") // http://dev.enble.site:8080/getCarDuration?start=1&goal=2
public ApiResponse<Integer> getDuration(@RequestParam("start") Long startLocationId,
@RequestParam("goal") Long goalLocationId) {

// 파라미터로 받은 locaion-id값 좌표로 변환
String start = naverPathService.getCoordinateById(startLocationId);
String goal = naverPathService.getCoordinateById(goalLocationId);

// 시작, 도착지 좌표 네이버 경로 서비스로 전달
Integer duration = naverPathService.getDuration(start, goal);

return ApiResponse.onSuccess(SuccessCode.PLAN_NAVER_GET_DURATION, duration);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.travelcompass.api.feign.Naver;

import com.travelcompass.api.location.service.LocationService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

@Service
public class NaverPathService {

private final NaverDurationClient naverDurationClient;
private final String clientId;
private final String clientSecret;
private final LocationService locationService;

public NaverPathService(NaverDurationClient naverDurationClient,
LocationService locationService,
@Value("${naver.directions.client-id}") String clientId,
@Value("${naver.directions.client-secret}") String clientSecret) {
this.naverDurationClient = naverDurationClient;
this.locationService = locationService;
this.clientId = clientId;
this.clientSecret = clientSecret;
}

public String getCoordinateById(Long id) {

String longitude = locationService.findById(id).getLongitude().toString();
String latitude = locationService.findById(id).getLatitude().toString();

return longitude + "," + latitude;
}

public int getDuration(String start, String goal) {
// 네이버 API에 요청을 보내기 전에 클라이언트 ID와 시크릿을 헤더에 설정
ResponseEntity<String> response = naverDurationClient.getDuration(start, goal, clientId, clientSecret);

// API Response로부터 body 뽑아내기
String body = response.getBody();
JSONObject json = new JSONObject(body);

// body에서 duration 추출하기
int duration = json.getJSONObject("route").getJSONArray("traoptimal")
.getJSONObject(0).getJSONObject("summary").getInt("duration");

return duration;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public enum SuccessCode implements BaseCode {
PLAN_LIKE_SUCCESS(HttpStatus.OK, "PLAN_2021", "여행계획 좋아요가 완료되었습니다."),
PLAN_UNLIKE_SUCCESS(HttpStatus.OK, "PLAN_2022", "여행계획 좋아요 취소가 완료되었습니다."),
PLAN_LIKE_COUNT_SUCCESS(HttpStatus.OK, "PLAN_2023", "좋아요 수가 조회되었습니다."),
PLAN_NAVER_GET_DURATION(HttpStatus.OK, "PLAN_2031", "네이버 경로탐색이 완료되었습니다.(단위: 1/1000초)"),

// Location
LOCATION_LIKE_SUCCESS(HttpStatus.OK, "LOCATION_2021", "장소 좋아요가 완료되었습니다."),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,20 @@ protected SecurityFilterChain securityFilterChain(
http
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(authHttp -> authHttp
.requestMatchers("/health", "/oauth2/authorization/naver", "/users/**", "/regions/**", "/locations/**", "/plans/**", "/me/**")
.requestMatchers(
"/health",
"/oauth2/authorization/naver", // 로그인
"/getCarDuration", // 자가용 소요시간 api
"/locations/regions/**", // 지역별 장소 리스트 조회
"/locations/**", // 장소 상세 조회
"/plans/search", // 여행계획 조회

"/users/**", // 로그아웃, 회원탈퇴
"/me/**" // 마이페이지
)
.permitAll()
.anyRequest().permitAll()
//.anyRequest().authenticated()
//.anyRequest().authenticated()

)
.oauth2Login(oauth2Login -> oauth2Login
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,19 +42,19 @@ protected void doFilterInternal(
} catch (io.jsonwebtoken.security.SecurityException | MalformedJwtException e) {
log.info("JWT 서명이 잘못되었습니다.");
jwtExceptionHandler(response, ErrorCode.TOKEN_INVALID);
// throw new GeneralException(ErrorCode.TOKEN_INVALID);
return;
} catch (ExpiredJwtException e) {
log.info("JWT 토큰이 만료되었습니다.");
jwtExceptionHandler(response, ErrorCode.TOKEN_EXPIRED);
// throw new GeneralException(ErrorCode.TOKEN_EXPIRED);
return;
} catch (UnsupportedJwtException e) {
log.info("지원되지 않는 토큰입니다.");
jwtExceptionHandler(response, ErrorCode.TOKEN_INVALID);
// throw new GeneralException(ErrorCode.TOKEN_INVALID);
return;
} catch (IllegalArgumentException e) {
log.info("잘못된 토큰입니다.");
jwtExceptionHandler(response, ErrorCode.TOKEN_INVALID);
// throw new GeneralException(ErrorCode.TOKEN_INVALID);
return;
}
}
filterChain.doFilter(request, response);
Expand Down
12 changes: 8 additions & 4 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,19 @@ spring:
- nickname
- email

# data:
# redis:
# host: ${REDIS_HOST}
# port: ${REDIS_PORT}
# 네이버 경로 api
naver:
directions:
api-url: https://naveropenapi.apigw.ntruss.com/map-direction
client-id: ${NAVER_DIRECTIONS_CLIENT_ID}
client-secret: ${NAVER_DIRECTIONS_CLIENT_SECRET}

# 도로명 주소 -> 좌표
kakao:
local:
key: ${KAKAO_LOCAL_KEY}

# 로그인 jwt
jwt:
secret: ${JWT_SECRET}
accessExpirationTime: ${JWT_EXPIRATION}
Expand Down

0 comments on commit a2e26b9

Please sign in to comment.