Skip to content

Commit

Permalink
✨ feat: 기상 특보 기능 재난문자 Api -> 특보 통보문 Api 변경
Browse files Browse the repository at this point in the history
  • Loading branch information
seheonnn authored May 21, 2024
2 parents e66a74b + 372afc1 commit 7b28c99
Show file tree
Hide file tree
Showing 12 changed files with 143 additions and 96 deletions.
3 changes: 3 additions & 0 deletions weather-service/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ dependencies {

//Springdoc
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.1.0'

// File
implementation 'org.apache.poi:poi-ooxml:5.2.0'
}

openApi {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@

import com.fasterxml.jackson.core.JsonProcessingException;
import com.waither.weatherservice.dto.request.AccuweatherTestRequest;
import com.waither.weatherservice.dto.request.AdvisoryRequest;
import com.waither.weatherservice.dto.request.AirTestRequest;
import com.waither.weatherservice.dto.request.ForeCastTestRequest;
import com.waither.weatherservice.dto.request.MsgTestRequest;
import com.waither.weatherservice.service.WeatherService;

import lombok.RequiredArgsConstructor;
Expand All @@ -36,9 +36,9 @@ public void createDailyWeatherTest(@RequestBody ForeCastTestRequest request) thr
weatherService.createDailyWeather(request.nx(), request.ny(), request.baseDate(), request.baseTime());
}

@PostMapping("/msg")
public void createDisasterMsgTest(@RequestBody MsgTestRequest request) throws URISyntaxException, IOException {
weatherService.createDisasterMsg(request.location());
@PostMapping("/advisory")
public void createWeatherAdvisory(@RequestBody AdvisoryRequest request) throws URISyntaxException, IOException {
weatherService.createWeatherAdvisory(request.latitude(), request.longitude());
}

@PostMapping("/air")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.waither.weatherservice.dto.request;

public record AdvisoryRequest(
double latitude,
double longitude
) {
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@RedisHash(value = "DisasterMessage", timeToLive = 86400L) // 유효시간: 24시간
public class DisasterMessage {
@RedisHash(value = "WeatherAdvisory", timeToLive = 86400L) // 유효시간: 24시간
public class WeatherAdvisory {

@Id
private String id;
private String message;

public String toString() {
return "DisasterMessage{" +
return "WeatherAdvisory{" +
"message='" + message + '\'' +
'}';
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
package com.waither.weatherservice.gps;

import java.io.IOException;
import java.io.InputStream;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;

import com.waither.weatherservice.exception.WeatherExceptionHandler;
import com.waither.weatherservice.response.WeatherErrorCode;

@Component
public class GpsTransfer {

Expand Down Expand Up @@ -92,4 +102,42 @@ public LatXLngY convertGridToGps(double x, double y) {
.y(y)
.build();
}

// ex) lat = 37.57142000, lon = 126.96580000 -> 108
public String convertGpsToRegionCode(double lat, double lon) {
String regionCode = null;
try {
InputStream inputStream = getClass().getResourceAsStream("/api/Region.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt(0); // 시트 인덱스, 첫 번째 시트를 가져옴

for (int i = 2; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
if (row != null) {
Cell lonCell = row.getCell(3);
Cell latCell = row.getCell(4);

// 셀이 비어 있는지 확인
if (lonCell != null && latCell != null) {
String lonValue = lonCell.toString().replace(",", "");
String latValue = latCell.toString().replace(",", "");

double rowLon = Double.parseDouble(lonValue);
double rowLat = Double.parseDouble(latValue);

// 위도 경도에 일치하는 지역코드
if (lon == rowLon && lat == rowLat) {
String stnId = row.getCell(0).toString();
regionCode = stnId;
break; // 일치하는 stn_id를 찾으면 반복 종료
}
}
}
}
workbook.close();
} catch (IOException e) {
throw new WeatherExceptionHandler(WeatherErrorCode.WEATHER_MAIN_ERROR);
}
return regionCode;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,74 +3,60 @@
import java.util.List;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

import lombok.Getter;

@Getter
@JsonIgnoreProperties(ignoreUnknown = true)
public class MsgOpenApiResponse {

@JsonProperty("DisasterMsg2")
private List<MsgData> disasterMsg;
private Response response;

@Getter
@JsonIgnoreProperties(ignoreUnknown = true)
public static class MsgData {
@JsonProperty("head")
private List<HeadData> head;
@JsonProperty("row")
private List<RowData> row;
public static class Response {
private Header header;
private Body body;
}

@Getter
@JsonIgnoreProperties(ignoreUnknown = true)
public static class HeadData {
@JsonProperty("totalCount")
public static class Header {
private String resultCode;
private String resultMsg;
}

@Getter
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Body {
private String dataType;
private Items items;
private int pageNo;
private int numOfRows;
private int totalCount;
@JsonProperty("numOfRows")
private String numOfRows;
@JsonProperty("pageNo")
private String pageNo;
@JsonProperty("type")
private String type;
@JsonProperty("RESULT")
private ResultData resultData;
}

@Getter
@JsonIgnoreProperties(ignoreUnknown = true)
public static class ResultData {
@JsonProperty("resultCode")
private String resultCode;
@JsonProperty("resultMsg")
private String resultMsg;
public static class Items {
private List<Item> item;
}

@Getter
@JsonIgnoreProperties(ignoreUnknown = true)
public static class RowData {
@JsonProperty("create_date")
private String createDate;
@JsonProperty("location_id")
private String locationId;
@JsonProperty("location_name")
private String locationName;
@JsonProperty("md101_sn")
private String md101Sn;
@JsonProperty("msg")
private String msg;
@JsonProperty("send_platform")
private String sendPlatform;
public static class Item {
private String stnId;
private String title;
private String tmFc;
private String tmSeq;

@Override
public String toString() {
return "RowData{" +
"createDate='" + createDate + '\'' +
", locationId='" + locationId + '\'' +
", locationName='" + locationName + '\'' +
", md101Sn='" + md101Sn + '\'' +
", msg='" + msg + '\'' +
", sendPlatform='" + sendPlatform + '\'' +
return "Item{" +
"stnId='" + stnId + '\'' +
", title='" + title + '\'' +
", tmFc='" + tmFc + '\'' +
", tmSeq='" + tmSeq + '\'' +
'}';
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
Expand All @@ -28,12 +29,8 @@
@RequiredArgsConstructor
public class OpenApiUtil {

public static final String ENCODING = "UTF-8";
public static final String RESPONSE_EXCEPTION_MSG = "Response is null";
@Value("${openapi.forecast.key}")
private String forecastKey;
@Value("${openapi.disasterMsg.key}")
private String disasterMsgKey;

@Value("${openapi.accuweather.key}")
private String accuweatherKey;
Expand Down Expand Up @@ -101,22 +98,24 @@ public String apiResponseStringFilter(List<ForeCastOpenApiResponse.Item> items,
}

// 재난 문자 Api
public List<MsgOpenApiResponse.RowData> callDisasterMsgApi(String location) throws
public List<MsgOpenApiResponse.Item> callAdvisoryApi(String location, String today) throws
URISyntaxException,
IOException {

WebClient webClient = WebClient.create();

String uriString = "http://apis.data.go.kr/1741000/DisasterMsg4/getDisasterMsg2List" +
"?" + URLEncoder.encode("serviceKey", ENCODING) + "=" + disasterMsgKey +
"&" + URLEncoder.encode("pageNo", ENCODING) + "=" + URLEncoder.encode("1", ENCODING) +
"&" + URLEncoder.encode("numOfRows", ENCODING) + "=" + URLEncoder.encode("2", ENCODING) +
"&" + URLEncoder.encode("type", ENCODING) + "=" + URLEncoder.encode("json", ENCODING) +
"&" + URLEncoder.encode("location_name", ENCODING) + "=" + URLEncoder.encode(location, ENCODING);
String uriString = "http://apis.data.go.kr/1360000/WthrWrnInfoService/getWthrWrnList" +
"?serviceKey=" + forecastKey +
"&numOfRows=" + "10" +
"&pageNo=" + "1" +
"&dataType=" + "JSON" +
"&stnId=" + location +
"&fromTmFc=" + today +
"&toTmFc=" + today;

URI uri = new URI(uriString);

log.info("[*] 재난 문자 Api : {}", uri);
log.info("[*] 기상 특보 Api : {}", uri);

String responseString = webClient.get()
.uri(uri)
Expand All @@ -131,19 +130,26 @@ public List<MsgOpenApiResponse.RowData> callDisasterMsgApi(String location) thro
.block();

ObjectMapper objectMapper = new ObjectMapper();
MsgOpenApiResponse response = objectMapper.readValue(responseString, MsgOpenApiResponse.class);
MsgOpenApiResponse.Response response = objectMapper.readValue(responseString, MsgOpenApiResponse.class)
.getResponse();

if (response.getDisasterMsg().get(0).getHead().get(2).getResultData().getResultCode().equals("INFO-0")) {
return response.getDisasterMsg().get(1).getRow();
if (response.getHeader().getResultCode().equals("00")) {
return response.getBody().getItems().getItem();
} else if (response.getHeader().getResultCode().equals("03")) {
log.info("특보 내용 없음");
throw new WeatherExceptionHandler(WeatherErrorCode.WEATHER_OPENAPI_ERROR);
} else {
String resultMsg = response.getDisasterMsg().get(0).getHead().get(2).getResultData().getResultMsg();
log.info("[*] OpenApi Error : {}", resultMsg);
log.info("특보 오류");
throw new WeatherExceptionHandler(WeatherErrorCode.WEATHER_OPENAPI_ERROR);
}
}

// TODO 재난 문자 필터 (날씨 정보만 추출)
public String convertLocalDateToString(LocalDate localDate) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
return localDate.format(formatter);
}

// TODO AccuWeather 대기 정보로 변경 예정
public List<AirKoreaOpenApiResponse.Items> callAirKorea(String searchDate) throws URISyntaxException {
int pageNo = 1;
int numOfRows = 10;
Expand Down Expand Up @@ -194,7 +200,6 @@ public Map<String, String> parseAirKoreaResponseToMap(String data) {
.map(s -> s.split(" : "))
.collect(HashMap::new, (m, arr) -> m.put(arr[0], arr[1]), HashMap::putAll);

// TODO 삭제 예정
map.forEach((key, value) -> log.info(key + " -> " + value));

return map;
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.waither.weatherservice.redis;

import org.springframework.data.repository.CrudRepository;

import com.waither.weatherservice.entity.WeatherAdvisory;

public interface WeatherAdvisoryRepository extends CrudRepository<WeatherAdvisory, String> {
}
Loading

0 comments on commit 7b28c99

Please sign in to comment.