Skip to content

Commit

Permalink
Merge pull request #27 from KUIT-Couphone/feature/store
Browse files Browse the repository at this point in the history
feat: gps 좌표계 epsg 5181 변환 기능 추가
  • Loading branch information
limsubinn authored Aug 8, 2023
2 parents 5ac3510 + dea33fd commit aa1fe30
Show file tree
Hide file tree
Showing 13 changed files with 130 additions and 58 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -103,4 +103,4 @@ $RECYCLE.BIN/
# akfrdma0125#
convention.md

# End of https://www.toptal.com/developers/gitignore/api/windows,macos
# End of https://www.toptal.com/developers/gitignore/api/windows,macos
8 changes: 6 additions & 2 deletions appspec.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@ permissions:
owner: ubuntu
group: ubuntu
hooks:
AfterInstall:
- location: scripts/deploy.sh
AfterInstall: # CodeDeploy의 AfterInstall 단계에서 실행
- location: scripts/stop.sh # hooks에서 실행할 스크립트의 위치
timeout: 60 # 스크립트 실행에 허용되는 최대 시간, 넘으면 배포 실패
runas: ubuntu # 스크립트를 실행하는 사용자
ApplicationStart: # CodeDeploy의 ApplicationStart 단계에서 실행
- location: scripts/start.sh
timeout: 60
runas: ubuntu
4 changes: 4 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ java {
sourceCompatibility = '17'
}

jar {
enabled = false
}

configurations {
compileOnly {
extendsFrom annotationProcessor
Expand Down
22 changes: 0 additions & 22 deletions scripts/deploy.sh

This file was deleted.

21 changes: 21 additions & 0 deletions scripts/start.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#!/usr/bin/env bash

PROJECT_ROOT="/home/ubuntu/couphone"
JAR_FILE="$PROJECT_ROOT/build/libs/couphone-server-0.0.1-SNAPSHOT.jar" # 여기서 프로젝트 이름은 일단 원하는 프로젝트 이름으로 설정해주세요. 밑에서 추가 설명하겠습니다.

APP_LOG="$PROJECT_ROOT/application.log"
ERROR_LOG="$PROJECT_ROOT/error.log"
DEPLOY_LOG="$PROJECT_ROOT/deploy.log"

TIME_NOW=$(date +%c)

# build 파일 복사
echo "$TIME_NOW > $JAR_FILE 파일 복사" >> $DEPLOY_LOG
cp $PROJECT_ROOT/build/libs/*.jar $JAR_FILE

# jar 파일 실행
echo "$TIME_NOW > $JAR_FILE 파일 실행" >> $DEPLOY_LOG
nohup java -jar $JAR_FILE > $APP_LOG 2> $ERROR_LOG &

CURRENT_PID=$(pgrep -f $JAR_FILE)
echo "$TIME_NOW > 실행된 프로세스 아이디 $CURRENT_PID 입니다." >> $DEPLOY_LOG
19 changes: 19 additions & 0 deletions scripts/stop.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#!/usr/bin/env bash

PROJECT_ROOT="/home/ubuntu/couphone"
JAR_FILE="$PROJECT_ROOT/build/libs/couphone-server-0.0.1-SNAPSHOT.jar" # 여기서 프로젝트 이름은 일단 원하는 프로젝트 이름으로 설정해주세요. 밑에서 추가 설명하겠습니다.

DEPLOY_LOG="$PROJECT_ROOT/deploy.log"

TIME_NOW=$(date +%c)

# 현재 구동 중인 애플리케이션 pid 확인
CURRENT_PID=$(pgrep -f $JAR_FILE)

# 프로세스가 켜져 있으면 종료
if [ -z $CURRENT_PID ]; then
echo "$TIME_NOW > 현재 실행중인 애플리케이션이 없습니다" >> $DEPLOY_LOG
else
echo "$TIME_NOW > 실행중인 $CURRENT_PID 애플리케이션 종료 " >> $DEPLOY_LOG
kill -15 $CURRENT_PID
fi
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import com.example.couphoneserver.common.exception.StoreException;
import com.example.couphoneserver.common.response.BaseResponse;
import com.example.couphoneserver.dto.store.LocationInfo;
import com.example.couphoneserver.dto.store.PostNearbyStoreResponse;
import com.example.couphoneserver.dto.store.GetNearbyStoreResponse;
import com.example.couphoneserver.dto.store.PostStoreRequest;
import com.example.couphoneserver.dto.store.PostStoreResponse;
import com.example.couphoneserver.service.StoreService;
Expand Down Expand Up @@ -65,7 +65,7 @@ public BaseResponse<Coordinate> translateCoordinate(@Parameter(name = "query", d
@GetMapping("/nearby")
@Operation(summary = "좌표 중심 가게 반환", description = "query string에 위도, 경도, 버튼 여부를 보내면 주변 가게 리스트를 반환합니다. 좌표게: epsg:5181",
security = @SecurityRequirement(name = "bearerAuth"))
public BaseResponse<List<PostNearbyStoreResponse>> translateCoordinate(
public BaseResponse<List<GetNearbyStoreResponse>> translateCoordinate(
@Parameter(name = "longitude", description = "경도", example = "207005.189144674", in = ParameterIn.QUERY) @RequestParam Double longitude,
@Parameter(name = "latitude", description = "위도", example = "449492.810069438", in = ParameterIn.QUERY) @RequestParam Double latitude,
@Parameter(name = "is1km", description = "버튼 누른 경우 true", in = ParameterIn.QUERY) @RequestParam Boolean is1km,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,23 +1,21 @@
package com.example.couphoneserver.dto.store;

import com.example.couphoneserver.domain.entity.Brand;
import com.example.couphoneserver.dto.brand.GetBrandResponse;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
public class PostNearbyStoreResponse {
public class GetNearbyStoreResponse {
private Long store_id;
private String name;
private Long brand_id;
private GetBrandResponse getBrandResponse;
private double distance;

@Builder
public PostNearbyStoreResponse(Long store_id, String name, Long brand_id) {
public GetNearbyStoreResponse(Long store_id, String name, Long brand_id) {
this.store_id = store_id;
this.name = name;
this.brand_id = brand_id;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.example.couphoneserver.repository.mappingInterface;

import com.example.couphoneserver.common.datatype.Coordinate;
import com.example.couphoneserver.dto.store.PostNearbyStoreResponse;
import com.example.couphoneserver.dto.store.GetNearbyStoreResponse;

public interface StoreInfoMapping {
Long getStore_id();
Expand All @@ -17,8 +17,8 @@ default Coordinate translateCoordinate(){
.build();
}

default PostNearbyStoreResponse translateResponse(){
return PostNearbyStoreResponse.builder()
default GetNearbyStoreResponse translateResponse(){
return GetNearbyStoreResponse.builder()
.store_id(getStore_id())
.name(getName())
.brand_id(getBrand_id())
Expand Down
30 changes: 20 additions & 10 deletions src/main/java/com/example/couphoneserver/service/StoreService.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,13 @@
import com.example.couphoneserver.domain.entity.Store;
import com.example.couphoneserver.dto.brand.GetBrandResponse;
import com.example.couphoneserver.dto.store.LocationInfo;
import com.example.couphoneserver.dto.store.PostNearbyStoreResponse;
import com.example.couphoneserver.dto.store.GetNearbyStoreResponse;
import com.example.couphoneserver.dto.store.PostStoreRequest;
import com.example.couphoneserver.dto.store.PostStoreResponse;
import com.example.couphoneserver.repository.BrandRepository;
import com.example.couphoneserver.repository.CouponItemRepository;
import com.example.couphoneserver.repository.StoreRepository;
import com.example.couphoneserver.utils.CoordinateConverter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
Expand All @@ -35,6 +36,7 @@ public class StoreService {
private final BrandRepository brandRepository;
private final CouponItemRepository couponItemRepository;
private final MemberService memberService;
private final CoordinateConverter coordinateConverter;

private static final int ELEMENT = 4;

Expand All @@ -55,27 +57,35 @@ public PostStoreResponse save(PostStoreRequest request) {
/*
가게 조회
*/
public List<PostNearbyStoreResponse> findNearbyStores(Principal principal, LocationInfo request){
List<PostNearbyStoreResponse> storeList = getCandidateStoreList(request);
Collections.sort(storeList, new Comparator<PostNearbyStoreResponse>() {
public List<GetNearbyStoreResponse> findNearbyStores(Principal principal, LocationInfo request){
translateEPSG5181(request);
List<GetNearbyStoreResponse> storeList = getCandidateStoreList(request);
Collections.sort(storeList, new Comparator<GetNearbyStoreResponse>() {
@Override
public int compare(PostNearbyStoreResponse o1, PostNearbyStoreResponse o2) {
public int compare(GetNearbyStoreResponse o1, GetNearbyStoreResponse o2) {
return o1.getDistance() > o2.getDistance()? 1: -1;
}
});
log.info(String.valueOf(storeList.size()));
int numOfElement = storeList.size()>=ELEMENT?ELEMENT:storeList.size();

List<PostNearbyStoreResponse> resultList = storeList.subList(0,numOfElement);
List<GetNearbyStoreResponse> resultList = storeList.subList(0,numOfElement);

for (PostNearbyStoreResponse response: resultList) {
for (GetNearbyStoreResponse response: resultList) {
response.setGetBrandResponse(getGetBrandResponse(principal, response.getBrand_id()));
}

return resultList;
}

private List<PostNearbyStoreResponse> getCandidateStoreList(LocationInfo request) {
private void translateEPSG5181(LocationInfo request) {
String address = coordinateConverter.getAddress(request.getLongitude(), request.getLatitude());
Coordinate coordinate = coordinateConverter.getCoordinate(address);
request.setLongitude(coordinate.getLongitude());
request.setLatitude(coordinate.getLatitude());
}

private List<GetNearbyStoreResponse> getCandidateStoreList(LocationInfo request) {
request.setDistance();
double x = request.getLongitude();
double y = request.getLatitude();
Expand All @@ -84,9 +94,9 @@ private List<PostNearbyStoreResponse> getCandidateStoreList(LocationInfo request
double maxLongitude = x + radius;
double minLatitude = y - radius;
double maxLatitude = y + radius;
List<PostNearbyStoreResponse> StoreList = new ArrayList<>();
List<GetNearbyStoreResponse> StoreList = new ArrayList<>();
storeRepository.findNearbyStores(minLongitude,maxLongitude,minLatitude,maxLatitude).stream().forEach(c -> {
PostNearbyStoreResponse response = c.translateResponse();
GetNearbyStoreResponse response = c.translateResponse();
Coordinate coordinate = c.translateCoordinate();
response.setDistance(calculateDistance(x,y,coordinate));
StoreList.add(response);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.example.couphoneserver.common.exception.StoreException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
Expand All @@ -28,15 +29,16 @@ public class CoordinateConverter {

private String searchType = "road";

private String epsg = "epsg:5181";
private static final String GETCOORD = "epsg:5181";
private static final String GETADDRESS = "epsg:4326";
/*
도로명 주소 필수!
*/
public Coordinate getCoordinate(String address){

String searchAddr = address;

StringBuilder sb = getURL(searchAddr);
StringBuilder sb = getURL("getcoord",searchAddr);

BufferedReader reader;

Expand All @@ -54,25 +56,61 @@ public Coordinate getCoordinate(String address){
String x = jspoitn.get("x").toString();
String y = jspoitn.get("y").toString();

System.out.println(x);
System.out.println(y);

return new Coordinate(Double.parseDouble(x),Double.parseDouble(y));
} catch (StoreException | ParseException | IOException e) {
throw new StoreException(COORDINATE_NOT_FOUND,e.getMessage());
}
}

private StringBuilder getURL(String searchAddr) {

public String getAddress(Double x, Double y){

String coordinate = x.toString()+","+y.toString();

StringBuilder sb = getURL("getAddress",coordinate);

BufferedReader reader;

try {
URL url = new URL(sb.toString());
reader = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));

JSONParser jspa = new JSONParser();
JSONObject jsob = (JSONObject) jspa.parse(reader);
JSONObject jsrs = (JSONObject) jsob.get("response");

JSONArray jsonArray = (JSONArray) jsrs.get("result");
JSONObject jsonfor = new JSONObject();

String address = "";

for (int i = 0; i< jsonArray.size(); i++){
jsonfor = (JSONObject) jsonArray.get(i);
address = (String) jsonfor.get("text");
log.info(address);
}

return address;
} catch (StoreException | ParseException | IOException e) {
throw new StoreException(COORDINATE_NOT_FOUND,e.getMessage());
}
}

private StringBuilder getURL(String request, String query) {
StringBuilder sb = new StringBuilder("https://api.vworld.kr/req/address");
sb.append("?service=address");
sb.append("&request=getCoord");
sb.append("&request="+request);
sb.append("&format=json");
sb.append("&crs=" + epsg);
sb.append("&key=" + apikey);
sb.append("&type=" + searchType);
sb.append("&simple=true");
sb.append("&address=" + URLEncoder.encode(searchAddr, StandardCharsets.UTF_8));
if(request.equals("getcoord")){
sb.append("&crs=" + GETCOORD);
sb.append("&address=" + URLEncoder.encode(query, StandardCharsets.UTF_8));
return sb;
}
sb.append("&crs=" + GETADDRESS);
sb.append("&point="+URLEncoder.encode(query, StandardCharsets.UTF_8));
return sb;
}
}
2 changes: 1 addition & 1 deletion src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -88,4 +88,4 @@ spring:
resources:
add-mappings: false
messages:
basename: errors
basename: errors
8 changes: 4 additions & 4 deletions src/main/resources/import.sql
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ INSERT INTO brand (brand_id, category_id, created_date, modified_date, brand_ima
INSERT INTO brand (brand_id, category_id, created_date, modified_date, brand_image_url, name, reward_description, status) VALUES (3, 1, '2023-07-30 10:00:00', '2023-07-30 10:05:00', 'https://example.com/images/brand2.jpg', '컴포즈 커피', '아이스 아메리카노 한 잔 무료 증정', 'ACTIVE');

-- 샘플 데이터 생성: store 테이블
INSERT INTO store (store_id, latitude, longitude, brand_id, created_date, modified_date, address, name, status) VALUES (1, 37.12345, -122.67890, 1, '2023-07-31 13:00:00', '2023-07-31 13:00:00', '서울특별시 메가커피 건대입구점 건대입구로 11111', '메가커피', 'ACTIVE');
INSERT INTO store (store_id, latitude, longitude, brand_id, created_date, modified_date, address, name, status) VALUES (2, 37.12345, -110.67890, 1, '2023-07-31 13:00:00', '2023-07-31 13:00:00', '서울특별시 메가커피 세종대입구점 세종대입구로 22222', '메가커피', 'ACTIVE');
INSERT INTO store (store_id, latitude, longitude, brand_id, created_date, modified_date, address, name, status) VALUES (3, 37.12345, -100.67890, 2, '2023-07-31 13:00:00', '2023-07-31 13:00:00', '서울특별시 컴포즈커피 건대입구점 건대입구로 11111', '컴포즈커피', 'ACTIVE');
INSERT INTO store (store_id, latitude, longitude, brand_id, created_date, modified_date, address, name, status) VALUES (1, 448095.451139153, 205901.648047968, 1, '2023-07-31 13:00:00', '2023-07-31 13:00:00', '서울특별시 광진구 자양제4동 7-25', '메가커피 건대입구점', 'ACTIVE');
INSERT INTO store (store_id, latitude, longitude, brand_id, created_date, modified_date, address, name, status) VALUES (2, 449854.142331362, 206314.864860792, 1, '2023-07-31 13:00:00', '2023-07-31 13:00:00', '서울특별시 광진구 군자동 373-5', '메가커피 세종대입구점', 'ACTIVE');
INSERT INTO store (store_id, latitude, longitude, brand_id, created_date, modified_date, address, name, status) VALUES (3, 449321.612722019, 206238.995849856, 2, '2023-07-31 13:00:00', '2023-07-31 13:00:00', '서울 광진구 능동로13길 30', '컴포즈커피 건대입구점', 'ACTIVE');

-- 샘플 데이터 생성: coupon_item 테이블
INSERT INTO coupon_item (coupon_item_id, stamp_count, brand_id, created_date, member_id, modified_date, status) VALUES (1, 5, 1, '2023-07-31 12:45:00', 1, '2023-07-31 12:45:00', 'INACTIVE');
INSERT INTO coupon_item (coupon_item_id, stamp_count, brand_id, created_date, member_id, modified_date, status) VALUES (2, 3, 2, '2023-07-30 11:00:00', 1, '2023-07-30 11:00:00', 'EXPIRED');
INSERT INTO coupon_item (coupon_item_id, stamp_count, brand_id, created_date, member_id, modified_date, status) VALUES (3, 4, 2, '2023-07-29 11:00:00', 1, '2023-07-30 11:00:00', 'INACTIVE');
INSERT INTO coupon_item (coupon_item_id, stamp_count, brand_id, created_date, member_id, modified_date, status) VALUES (4, 1, 2, '2023-07-28 11:00:00', 2, '2023-07-30 11:00:00', 'INACTIVE');
INSERT INTO coupon_item (coupon_item_id, stamp_count, brand_id, created_date, member_id, modified_date, status) VALUES (5, 10, 1, '2022-07-26 11:00:00', 2, '2022-07-30 11:00:00', 'ACTIVE');
INSERT INTO coupon_item (coupon_item_id, stamp_count, brand_id, created_date, member_id, modified_date, status) VALUES (5, 10, 1, '2023-07-26 11:00:00', 2, '2023-07-30 11:00:00', 'ACTIVE');

0 comments on commit aa1fe30

Please sign in to comment.