From 79b7fce8947b8d9a0d1998ec6c94e985b11058fd Mon Sep 17 00:00:00 2001 From: hyun-jung-joo Date: Fri, 6 Oct 2023 10:49:37 +0900 Subject: [PATCH] [REFACTOR] code refactoring - weather, prepare --- .../prepare/controller/PrepareController.java | 109 ++-- .../backend/prepare/dto/PrePareInfoDto.java | 13 +- .../backend/prepare/dto/PrepareDto.java | 84 +-- .../prepare/dto/PrepareNeedInfoDto.java | 7 +- .../prepare/dto/PrepareWeatherDto.java | 12 +- .../prepare/service/PrepareService.java | 594 +++++++++--------- .../weather/controller/AirController.java | 44 +- .../weather/controller/LivingController.java | 64 +- .../weather/controller/WeatherController.java | 178 +++--- .../haemil/backend/weather/dto/AirDto.java | 15 +- .../backend/weather/dto/AirInfoDto.java | 10 +- .../haemil/backend/weather/dto/LivingDto.java | 37 +- .../backend/weather/dto/LivingInfoDto.java | 4 +- .../backend/weather/dto/StationDto.java | 11 +- .../backend/weather/dto/StationInfoDto.java | 2 +- .../backend/weather/dto/TransferDto.java | 4 +- .../backend/weather/dto/WeatherDto.java | 39 +- .../backend/weather/dto/WeatherInfoDto.java | 9 +- .../backend/weather/service/AirService.java | 170 ++--- .../weather/service/LivingService.java | 242 +++---- .../weather/service/LocationService.java | 87 ++- .../weather/service/StationService.java | 109 ++-- .../weather/service/TransferService.java | 136 ++-- .../weather/service/WeatherService.java | 406 ++++++------ 24 files changed, 1202 insertions(+), 1184 deletions(-) diff --git a/src/main/java/com/haemil/backend/prepare/controller/PrepareController.java b/src/main/java/com/haemil/backend/prepare/controller/PrepareController.java index 97f26af..82ef087 100644 --- a/src/main/java/com/haemil/backend/prepare/controller/PrepareController.java +++ b/src/main/java/com/haemil/backend/prepare/controller/PrepareController.java @@ -1,10 +1,7 @@ package com.haemil.backend.prepare.controller; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; import com.haemil.backend.global.config.BaseException; import com.haemil.backend.global.config.BaseResponse; -import com.haemil.backend.global.config.ResponseStatus; import com.haemil.backend.prepare.dto.*; import com.haemil.backend.prepare.service.PrepareService; import com.haemil.backend.weather.controller.AirController; @@ -30,81 +27,75 @@ @RequiredArgsConstructor @RequestMapping("/prepare") public class PrepareController { - private final PrepareService prepareService; - private final WeatherController weatherController; - private final LivingController livingController; - private final AirController airController; + private final PrepareService prepareService; + private final WeatherController weatherController; + private final LivingController livingController; + private final AirController airController; - private PrepareDto fetchDataAndProcess(HttpServletRequest request) throws BaseException { - String latitude = request.getParameter("latitude"); - String longitude = request.getParameter("longitude"); + private PrepareDto fetchDataAndProcess(HttpServletRequest request) throws BaseException { + ResponseEntity weatherResponse = weatherController.sendGetRequest(request); - ResponseEntity weatherResponse = weatherController.sendGetRequest(request); + List todayTemps = weatherController.currentTimeData; + Map temps = weatherController.transformedData; // 최고 최저 온도 - List todayTemps = weatherController.currentTimeData; - Map temps = weatherController.transformedData; // 최고 최저 온도 + ResponseEntity airResponse = airController.sendGetRequest(request); + List todayAirs = airController.infoList; - ResponseEntity airResponse = airController.sendGetRequest(request); - List todayAirs = airController.infoList; + ResponseEntity livingResponse = livingController.sendGetRequest(request); + List todayLivings = livingController.infoList; - ResponseEntity livingResponse = livingController.sendGetRequest(request); - List todayLivings = livingController.infoList; + PrepareDto prepareDto = new PrepareDto(todayTemps, todayAirs, temps, todayLivings); + prepareService.filterWeatherData(todayTemps, prepareDto); + prepareService.filterAirData(todayAirs, prepareDto); - PrepareDto prepareDto = new PrepareDto(todayTemps, todayAirs, temps, todayLivings); - prepareService.filterWeatherData(todayTemps, prepareDto); - prepareService.filterAirData(todayAirs, prepareDto); + return prepareDto; + } - return prepareDto; - } - - @GetMapping("/send") - public ResponseEntity sendGetRequest(HttpServletRequest request) { - try { - PrepareDto prepareDto = fetchDataAndProcess(request); + @GetMapping("/send") + public ResponseEntity sendGetRequest(HttpServletRequest request) { + try { + PrepareDto prepareDto = fetchDataAndProcess(request); - List prepareDtoList = new ArrayList<>(); - prepareDtoList.add(prepareDto); + List prepareDtoList = new ArrayList<>(); + prepareDtoList.add(prepareDto); - List resultString = prepareService.ParsingJson(prepareDtoList); -// log.info("prePare_result = {}", resultString); // 외출 적합도 결과 log + List resultString = prepareService.ParsingJson(prepareDtoList); - return new BaseResponse<>(resultString).convert(); - } catch(BaseException e) { - return new BaseResponse<>(e.getStatus()).convert(); - } + return new BaseResponse<>(resultString).convert(); + } catch (BaseException e) { + return new BaseResponse<>(e.getStatus()).convert(); } + } - @GetMapping("/weather") - public ResponseEntity sendWeatherInfo(HttpServletRequest request) { - try { - PrepareDto prepareDto = fetchDataAndProcess(request); + @GetMapping("/weather") + public ResponseEntity sendWeatherInfo(HttpServletRequest request) { + try { + PrepareDto prepareDto = fetchDataAndProcess(request); - List prepareDtoList = new ArrayList<>(); - prepareDtoList.add(prepareDto); + List prepareDtoList = new ArrayList<>(); + prepareDtoList.add(prepareDto); - List resultString = prepareService.ParsingWeather(prepareDtoList); -// log.info("prePare_weather_result = {}", resultString); // 외출 - 날씨 관련 정보 + List resultString = prepareService.ParsingWeather(prepareDtoList); - return new BaseResponse<>(resultString).convert(); - } catch(BaseException e) { - return new BaseResponse<>(e.getStatus()).convert(); - } + return new BaseResponse<>(resultString).convert(); + } catch (BaseException e) { + return new BaseResponse<>(e.getStatus()).convert(); } + } - @GetMapping("/need") - public ResponseEntity sendNeedInfo(HttpServletRequest request) { - try { - PrepareDto prepareDto = fetchDataAndProcess(request); + @GetMapping("/need") + public ResponseEntity sendNeedInfo(HttpServletRequest request) { + try { + PrepareDto prepareDto = fetchDataAndProcess(request); - List prepareDtoList = new ArrayList<>(); - prepareDtoList.add(prepareDto); + List prepareDtoList = new ArrayList<>(); + prepareDtoList.add(prepareDto); - List resultString = prepareService.ParsingNeed(prepareDtoList); -// log.info("prePare_need_result = {}", resultString); // 외출 물품 정보 + List resultString = prepareService.ParsingNeed(prepareDtoList); - return new BaseResponse<>(resultString).convert(); - } catch(BaseException e) { - return new BaseResponse<>(e.getStatus()).convert(); - } + return new BaseResponse<>(resultString).convert(); + } catch (BaseException e) { + return new BaseResponse<>(e.getStatus()).convert(); } + } } diff --git a/src/main/java/com/haemil/backend/prepare/dto/PrePareInfoDto.java b/src/main/java/com/haemil/backend/prepare/dto/PrePareInfoDto.java index 960a5bf..5269352 100644 --- a/src/main/java/com/haemil/backend/prepare/dto/PrePareInfoDto.java +++ b/src/main/java/com/haemil/backend/prepare/dto/PrePareInfoDto.java @@ -1,12 +1,13 @@ package com.haemil.backend.prepare.dto; + import lombok.Data; @Data public class PrePareInfoDto { - private String pm10value; // 가장 최근꺼로 오늘꺼 미세먼지 수치 - private String clothes; // 기온별 옷차림 -> 옵션 ) ex. "민소매, 반팔, 반바지, 원피스" - private String feel_like; // 체감 온도 - private String uv; // 자외선 - private String result; // 외출 적합도 문장 -> 옵션 ) ex. "외출하기 좋은 날이네요" - private int percent; // 외출 적합도 퍼센트 + private String pm10value; // 가장 최근꺼로 오늘꺼 미세먼지 수치 + private String clothes; // 기온별 옷차림 -> 옵션 ) ex. "민소매, 반팔, 반바지, 원피스" + private String feel_like; // 체감 온도 + private String uv; // 자외선 + private String result; // 외출 적합도 문장 -> 옵션 ) ex. "외출하기 좋은 날이네요" + private int percent; // 외출 적합도 퍼센트 } diff --git a/src/main/java/com/haemil/backend/prepare/dto/PrepareDto.java b/src/main/java/com/haemil/backend/prepare/dto/PrepareDto.java index e6bc74e..f598cbf 100644 --- a/src/main/java/com/haemil/backend/prepare/dto/PrepareDto.java +++ b/src/main/java/com/haemil/backend/prepare/dto/PrepareDto.java @@ -1,4 +1,5 @@ package com.haemil.backend.prepare.dto; + import com.haemil.backend.weather.controller.WeatherController; import com.haemil.backend.weather.controller.AirController; import com.haemil.backend.weather.dto.AirInfoDto; @@ -13,46 +14,47 @@ @Data @Component public class PrepareDto { - private WeatherController weatherController; - private AirController airController; - private List todayTemps; - private List todayAirs; - private String maxTemp; // 오늘 최고 온도 - private String minTemp; // 오늘 최저 온도 - - // 현재 실시간(시간별) weather 정보 - private String tmp; // 1시간 온도 - private String pop; // 강수 확률 - private String pty; // 강수 형태 - private String pcp; // 1시간 강수량 - private String reh; // 습도 - private String sky; // 하늘 상태 - private String wsd; // 풍속(m/s) - - // 대기질 - private String pm10grade; // 가장 최근꺼로 오늘꺼 미세먼지 등급 - private String pm10value; // 가장 최근꺼로 오늘꺼 미세먼지 수치 - private String pm25grade; // 가장 최근꺼로 오늘꺼 초미세먼지 등급 - private String pm25value; // 가장 최근꺼로 오늘꺼 미세먼지 수치 - - // living - private String feelLike; // 체감 온도 - private String uv; // 자외선 - - public PrepareDto() { - } - - public PrepareDto(List todayTemps, List todayAirs, Map temps, List livings) { - this.todayTemps = todayTemps; - this.todayAirs = todayAirs; - String maxTemp = temps.get("max"); - String minTemp = temps.get("min"); - this.maxTemp = maxTemp; - this.minTemp = minTemp; - - if (!livings.isEmpty()) { - this.feelLike = livings.get(0).getFeels_like(); - this.uv = livings.get(0).getUvi(); - } + private WeatherController weatherController; + private AirController airController; + private List todayTemps; + private List todayAirs; + private String maxTemp; // 오늘 최고 온도 + private String minTemp; // 오늘 최저 온도 + + // 현재 실시간(시간별) weather 정보 + private String tmp; // 1시간 온도 + private String pop; // 강수 확률 + private String pty; // 강수 형태 + private String pcp; // 1시간 강수량 + private String reh; // 습도 + private String sky; // 하늘 상태 + private String wsd; // 풍속(m/s) + + // 대기질 + private String pm10grade; // 가장 최근꺼로 오늘꺼 미세먼지 등급 + private String pm10value; // 가장 최근꺼로 오늘꺼 미세먼지 수치 + private String pm25grade; // 가장 최근꺼로 오늘꺼 초미세먼지 등급 + private String pm25value; // 가장 최근꺼로 오늘꺼 미세먼지 수치 + + // living + private String feelLike; // 체감 온도 + private String uv; // 자외선 + + public PrepareDto( + List todayTemps, + List todayAirs, + Map temps, + List livings) { + this.todayTemps = todayTemps; + this.todayAirs = todayAirs; + String maxTemp = temps.get("max"); + String minTemp = temps.get("min"); + this.maxTemp = maxTemp; + this.minTemp = minTemp; + + if (!livings.isEmpty()) { + this.feelLike = livings.get(0).getFeels_like(); + this.uv = livings.get(0).getUvi(); } + } } diff --git a/src/main/java/com/haemil/backend/prepare/dto/PrepareNeedInfoDto.java b/src/main/java/com/haemil/backend/prepare/dto/PrepareNeedInfoDto.java index bffd642..565dd77 100644 --- a/src/main/java/com/haemil/backend/prepare/dto/PrepareNeedInfoDto.java +++ b/src/main/java/com/haemil/backend/prepare/dto/PrepareNeedInfoDto.java @@ -1,11 +1,12 @@ package com.haemil.backend.prepare.dto; + import lombok.Data; import org.springframework.stereotype.Component; @Data @Component public class PrepareNeedInfoDto { - private String mask; // 미세먼지 농도 값에 따른 마스크 착용 -> 옵션 ) 자율, 권고, 필수 - private String umbrella; // 강수량에 따른 우선 여부 - private String clothes; // 기온별 옷차림 -> 옵션 ) ex. "민소매, 반팔, 반바지, 원피스" + private String mask; // 미세먼지 농도 값에 따른 마스크 착용 -> 옵션 ) 자율, 권고, 필수 + private String umbrella; // 강수량에 따른 우선 여부 + private String clothes; // 기온별 옷차림 -> 옵션 ) ex. "민소매, 반팔, 반바지, 원피스" } diff --git a/src/main/java/com/haemil/backend/prepare/dto/PrepareWeatherDto.java b/src/main/java/com/haemil/backend/prepare/dto/PrepareWeatherDto.java index 3db79d4..624bbb0 100644 --- a/src/main/java/com/haemil/backend/prepare/dto/PrepareWeatherDto.java +++ b/src/main/java/com/haemil/backend/prepare/dto/PrepareWeatherDto.java @@ -6,12 +6,12 @@ @Data @Component public class PrepareWeatherDto { - private String pm10value; // 가장 최근꺼로 오늘꺼 미세먼지 수치 - private String pm25value; // 가장 최근꺼로 오늘꺼 미세먼지 수치 + private String pm10value; // 가장 최근꺼로 오늘꺼 미세먼지 수치 + private String pm25value; // 가장 최근꺼로 오늘꺼 미세먼지 수치 - private String pop; // 강수 확률 - private String pcp; // 1시간 강수량 + private String pop; // 강수 확률 + private String pcp; // 1시간 강수량 - private String wsd; // 풍속(m/s) - private String uv; // 자외선 + private String wsd; // 풍속(m/s) + private String uv; // 자외선 } diff --git a/src/main/java/com/haemil/backend/prepare/service/PrepareService.java b/src/main/java/com/haemil/backend/prepare/service/PrepareService.java index 1cf3205..a2d315c 100644 --- a/src/main/java/com/haemil/backend/prepare/service/PrepareService.java +++ b/src/main/java/com/haemil/backend/prepare/service/PrepareService.java @@ -1,7 +1,5 @@ package com.haemil.backend.prepare.service; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; import com.haemil.backend.global.config.BaseException; import com.haemil.backend.global.config.ResponseStatus; import com.haemil.backend.prepare.dto.PrePareInfoDto; @@ -13,7 +11,6 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; -import org.springframework.web.client.RestTemplate; import java.util.ArrayList; import java.util.List; @@ -22,340 +19,323 @@ @Service @RequiredArgsConstructor public class PrepareService { - private final RestTemplate restTemplate; - private final ObjectMapper objectMapper; - - public void filterWeatherData(List weatherInfoDtoList, PrepareDto prepareDto) { - for (WeatherInfoDto weatherInfoDto : weatherInfoDtoList) { - String category = weatherInfoDto.getCategory(); - - if (category.equals("TMP")) { - prepareDto.setTmp(weatherInfoDto.getFcstValue()); - } else if (category.equals("POP")) { - prepareDto.setPop(weatherInfoDto.getFcstValue()); - } else if (category.equals("PTY")) { - prepareDto.setPty(weatherInfoDto.getFcstValue()); - } else if (category.equals("PCP")) { - prepareDto.setPcp(weatherInfoDto.getFcstValue()); - } else if (category.equals("REH")) { - prepareDto.setReh(weatherInfoDto.getFcstValue()); - } else if (category.equals("SKY")) { - prepareDto.setSky(weatherInfoDto.getFcstValue()); - } else if (category.equals("WSD")) { - prepareDto.setWsd(weatherInfoDto.getFcstValue()); - } - } - } - public void filterAirData(List airInfoDto, PrepareDto prepareDto) { - AirInfoDto resultDto = airInfoDto.get(0); - prepareDto.setPm10grade(resultDto.getPm10Grade()); - prepareDto.setPm25grade(resultDto.getPm25Grade()); - prepareDto.setPm10value(resultDto.getPm10Value()); - prepareDto.setPm25value(resultDto.getPm25Value()); + public void filterWeatherData(List weatherInfoDtoList, PrepareDto prepareDto) { + for (WeatherInfoDto weatherInfoDto : weatherInfoDtoList) { + String category = weatherInfoDto.getCategory(); + + if (category.equals("TMP")) { + prepareDto.setTmp(weatherInfoDto.getFcstValue()); + } else if (category.equals("POP")) { + prepareDto.setPop(weatherInfoDto.getFcstValue()); + } else if (category.equals("PTY")) { + prepareDto.setPty(weatherInfoDto.getFcstValue()); + } else if (category.equals("PCP")) { + prepareDto.setPcp(weatherInfoDto.getFcstValue()); + } else if (category.equals("REH")) { + prepareDto.setReh(weatherInfoDto.getFcstValue()); + } else if (category.equals("SKY")) { + prepareDto.setSky(weatherInfoDto.getFcstValue()); + } else if (category.equals("WSD")) { + prepareDto.setWsd(weatherInfoDto.getFcstValue()); + } } + } - public List ParsingJson(List prepareDtoList) throws BaseException { - List prePareInfoDtoList = new ArrayList<>(); + public void filterAirData(List airInfoDto, PrepareDto prepareDto) { + AirInfoDto resultDto = airInfoDto.get(0); + prepareDto.setPm10grade(resultDto.getPm10Grade()); + prepareDto.setPm25grade(resultDto.getPm25Grade()); + prepareDto.setPm10value(resultDto.getPm10Value()); + prepareDto.setPm25value(resultDto.getPm25Value()); + } - for (PrepareDto prepareDto : prepareDtoList) { - PrePareInfoDto prePareInfoDto = new PrePareInfoDto(); + public List ParsingJson(List prepareDtoList) throws BaseException { + List prePareInfoDtoList = new ArrayList<>(); - prePareInfoDto.setPm10value(prepareDto.getPm10value()); -// log.info("pm10value = {}", prepareDto.getPm10value()); + for (PrepareDto prepareDto : prepareDtoList) { + PrePareInfoDto prePareInfoDto = new PrePareInfoDto(); - prePareInfoDto.setClothes(getClothesValue(prepareDto.getMaxTemp(), prepareDto.getMinTemp(), prepareDto.getTmp())); -// log.info("clothes = {}", getClothesValue(prepareDto.getMaxTemp(), prepareDto.getMinTemp(), prepareDto.getTmp())); + prePareInfoDto.setPm10value(prepareDto.getPm10value()); - prePareInfoDto.setFeel_like(prepareDto.getFeelLike()); -// log.info("feellike = {}", prepareDto.getFeelLike()); - prePareInfoDto.setUv(getUvStatus(prepareDto)); -// log.info("uv = {}", getUvStatus(prepareDto)); + prePareInfoDto.setClothes(getClothesValue(prepareDto.getMaxTemp(), prepareDto.getMinTemp())); - int percent = getPercentValue(prepareDto); - prePareInfoDto.setPercent(percent); -// log.info("percent = {}", percent); + prePareInfoDto.setFeel_like(prepareDto.getFeelLike()); + prePareInfoDto.setUv(getUvStatus(prepareDto)); - String result = getResultValue(percent); - prePareInfoDto.setResult(result); -// log.info("result = {}", result); + int percent = getPercentValue(prepareDto); + prePareInfoDto.setPercent(percent); - prePareInfoDtoList.add(prePareInfoDto); - } - return prePareInfoDtoList; - } + String result = getResultValue(percent); + prePareInfoDto.setResult(result); - public List ParsingNeed(List prepareDtoList) throws BaseException { - List prePareInfoDtoList = new ArrayList<>(); + prePareInfoDtoList.add(prePareInfoDto); + } + return prePareInfoDtoList; + } - for (PrepareDto prepareDto : prepareDtoList) { - PrepareNeedInfoDto prePareInfoDto = new PrepareNeedInfoDto(); + public List ParsingNeed(List prepareDtoList) + throws BaseException { + List prePareInfoDtoList = new ArrayList<>(); - prePareInfoDto.setMask(getMaskValue(prepareDto.getPm10grade(), prepareDto.getPm25grade())); - prePareInfoDto.setUmbrella(needUmbrella(prepareDto.getPop(), prepareDto.getPty())); - prePareInfoDto.setClothes(getClothesValue(prepareDto.getMaxTemp(), prepareDto.getMinTemp(), prepareDto.getTmp())); + for (PrepareDto prepareDto : prepareDtoList) { + PrepareNeedInfoDto prePareInfoDto = new PrepareNeedInfoDto(); - prePareInfoDtoList.add(prePareInfoDto); - } + prePareInfoDto.setMask(getMaskValue(prepareDto.getPm10grade(), prepareDto.getPm25grade())); + prePareInfoDto.setUmbrella(needUmbrella(prepareDto.getPop(), prepareDto.getPty())); + prePareInfoDto.setClothes(getClothesValue(prepareDto.getMaxTemp(), prepareDto.getMinTemp())); - return prePareInfoDtoList; + prePareInfoDtoList.add(prePareInfoDto); } - public List ParsingWeather(List prepareDtoList) throws BaseException { - List prePareInfoDtoList = new ArrayList<>(); - - for (PrepareDto prepareDto : prepareDtoList) { - PrepareWeatherDto prePareInfoDto = new PrepareWeatherDto(); - prePareInfoDto.setPm10value(prepareDto.getPm10value()); - prePareInfoDto.setPm25value(prepareDto.getPm25value()); - prePareInfoDto.setPop(prepareDto.getPop()); - prePareInfoDto.setWsd(prepareDto.getWsd()); - prePareInfoDto.setPcp(prepareDto.getPcp()); - prePareInfoDto.setUv(prepareDto.getUv()); - - prePareInfoDtoList.add(prePareInfoDto); - } - return prePareInfoDtoList; - } + return prePareInfoDtoList; + } - private String convertObjectToJson(Object object) throws JsonProcessingException { - return objectMapper.writeValueAsString(object); - } + public List ParsingWeather(List prepareDtoList) + throws BaseException { + List prePareInfoDtoList = new ArrayList<>(); + for (PrepareDto prepareDto : prepareDtoList) { + PrepareWeatherDto prePareInfoDto = new PrepareWeatherDto(); + prePareInfoDto.setPm10value(prepareDto.getPm10value()); + prePareInfoDto.setPm25value(prepareDto.getPm25value()); + prePareInfoDto.setPop(prepareDto.getPop()); + prePareInfoDto.setWsd(prepareDto.getWsd()); + prePareInfoDto.setPcp(prepareDto.getPcp()); + prePareInfoDto.setUv(prepareDto.getUv()); - // 마스크 착용 여부를 판단하는 메서드 - private String getMaskValue(String pm10grade, String pm25grade) { - double result = 0.0; - - if (pm10grade != "null" && pm25grade != "null") { - // 미세먼지 + 초미세먼지 의 평균으로 비교 - int pm10gradeInt = Integer.parseInt(pm10grade); - int pm25gradeInt = Integer.parseInt(pm25grade); - result = (pm10gradeInt + pm25gradeInt) / 2; - } - else if (pm10grade == "null" && pm25grade != "null") { - int pm25gradeInt = Integer.parseInt(pm25grade); - result = pm25gradeInt; - } - else if (pm25grade == "null" && pm10grade != "null") { - int pm10gradeInt = Integer.parseInt(pm10grade); - result = pm10gradeInt; - } - - if (result < 2) - return "자율"; - else if (result < 3) - return "권고"; - else - return "필수"; + prePareInfoDtoList.add(prePareInfoDto); } - - private String getUvStatus(PrepareDto prepareDto) { - int uvIndex = Integer.parseInt(prepareDto.getUv()); // 자외선 지수 - - if (uvIndex <= 2) { - return "아주 좋음"; - } else if (uvIndex >= 3 && uvIndex <= 5) { - return "좋음"; - } else if (uvIndex >= 6 && uvIndex <= 7) { - return "보통"; - } else if (uvIndex >= 8 && uvIndex <= 10) { - return "나쁨"; - } else { - return "아주 나쁨"; - } + return prePareInfoDtoList; + } + + // 마스크 착용 여부를 판단하는 메서드 + private String getMaskValue(String pm10grade, String pm25grade) { + double result = 0.0; + + if (pm10grade != "null" && pm25grade != "null") { + // 미세먼지 + 초미세먼지 의 평균으로 비교 + int pm10gradeInt = Integer.parseInt(pm10grade); + int pm25gradeInt = Integer.parseInt(pm25grade); + result = (pm10gradeInt + pm25gradeInt) / 2; + } else if (pm10grade == "null" && pm25grade != "null") { + int pm25gradeInt = Integer.parseInt(pm25grade); + result = pm25gradeInt; + } else if (pm25grade == "null" && pm10grade != "null") { + int pm10gradeInt = Integer.parseInt(pm10grade); + result = pm10gradeInt; } - // 기온에 따른 옷차림을 판단하는 메서드 - //평균온도로 - private String getClothesValue(String maxTemp, String minTemp, String temp) { - // 실시간 온도로 가져옴 -// double todayTemp = Double.parseDouble(temp); - // 또는 평균 온도로도 가능하게 - double todayTemp = (Double.parseDouble(maxTemp) + Double.parseDouble(minTemp)) / 2; - - if (todayTemp >= 28.0) { - return "민소매, 반팔, 반바지, 원피스"; - } else if (todayTemp >= 23.0) { - return "반팔, 얇은 셔츠, 반바지, 면바지"; - } else if (todayTemp >= 20.0) { - return "얇은 가디건, 긴팔, 면바지, 청바지"; - } else if (todayTemp >= 17.0) { - return "얇은 니트, 맨투맨, 가디건, 청바지"; - } else if (todayTemp >= 12.0) { - return "자켓, 가디건, 야상, 스타킹, 청바지, 면바지"; - } else if (todayTemp >= 9.0) { - return "자켓, 트렌치코트, 야상, 니트, 청바지, 스타킹"; - } else if (todayTemp >= 5.0) { - return "코트, 가죽자켓, 히트텍, 니트, 레깅스"; - } else { - return "패딩, 두꺼운코트, 목도리, 기모제품"; - } + if (result < 2) return "자율"; + else if (result < 3) return "권고"; + else return "필수"; + } + + private String getUvStatus(PrepareDto prepareDto) { + int uvIndex = Integer.parseInt(prepareDto.getUv()); // 자외선 지수 + + if (uvIndex <= 2) { + return "아주 좋음"; + } else if (uvIndex >= 3 && uvIndex <= 5) { + return "좋음"; + } else if (uvIndex >= 6 && uvIndex <= 7) { + return "보통"; + } else if (uvIndex >= 8 && uvIndex <= 10) { + return "나쁨"; + } else { + return "아주 나쁨"; + } + } + + // 기온에 따른 옷차림을 판단하는 메서드 + private String getClothesValue(String maxTemp, String minTemp) { + double todayTemp = (Double.parseDouble(maxTemp) + Double.parseDouble(minTemp)) / 2; + + if (todayTemp >= 28.0) { + return "민소매, 반팔, 반바지, 원피스"; + } else if (todayTemp >= 23.0) { + return "반팔, 얇은 셔츠, 반바지, 면바지"; + } else if (todayTemp >= 20.0) { + return "얇은 가디건, 긴팔, 면바지, 청바지"; + } else if (todayTemp >= 17.0) { + return "얇은 니트, 맨투맨, 가디건, 청바지"; + } else if (todayTemp >= 12.0) { + return "자켓, 가디건, 야상, 스타킹, 청바지, 면바지"; + } else if (todayTemp >= 9.0) { + return "자켓, 트렌치코트, 야상, 니트, 청바지, 스타킹"; + } else if (todayTemp >= 5.0) { + return "코트, 가죽자켓, 히트텍, 니트, 레깅스"; + } else { + return "패딩, 두꺼운코트, 목도리, 기모제품"; + } + } + + // 강수 확률과 형태에 따른 우산 우선 여부를 판단하는 메서드 + private String needUmbrella(String pop, String pty) { + if (pop.equals("0") && pty.equals("0")) { + return "우산 필요 없음"; // 눈이나 비가 안옴 + } else { + return "우산 필요"; // 눈이나 비가 옴 + } + } + + public int getPercentValue(PrepareDto prepareDto) throws BaseException { + // 구현 방법에 따라 외출 적합도를 판단하여 해당 퍼센트 값을 반환 + int percentValue = 50; // 디폴트 값 0 + + try { + // 현재 실시간 weather 정보 + int temperature = Integer.parseInt(prepareDto.getTmp()); // 기온 + int precipitationProbability = Integer.parseInt(prepareDto.getPop()); // 강수확률 + int humidity = Integer.parseInt(prepareDto.getReh()); // 습도 + String airQuality = + airQualityScore(prepareDto.getPm10grade(), prepareDto.getPm25grade()); // 대기질 등급 계산 + + // Temperature calculation + if (temperature >= 20 && temperature <= 25) { + percentValue += 10; + } else if ((temperature >= 15 && temperature < 20) + || (temperature > 25 && temperature <= 30)) { + percentValue += 5; + } else if ((temperature >= 10 && temperature < 15) + || (temperature > 30 && temperature <= 35)) { + percentValue -= 5; + } else if ((temperature >= 0 && temperature < 10) + || (temperature > 35 && temperature <= 40)) { + percentValue -= 10; + } else if (temperature < 0 || temperature >= 40) { + percentValue -= 20; + } + + // Precipitation probability calculation + if (precipitationProbability <= 30) { + percentValue += 10; + } else if (precipitationProbability <= 50) { + percentValue += 5; + } else if (precipitationProbability <= 70) { + percentValue += 0; + } else if (precipitationProbability <= 80) { + percentValue -= 5; + } else if (precipitationProbability > 80) { + percentValue -= 10; + } + + // Humidity calculation + if (humidity >= 30 && humidity <= 50) { + percentValue += 10; + } else if ((humidity >= 20 && humidity < 30) || (humidity > 50 && humidity <= 60)) { + percentValue += 5; + } else if ((humidity >= 10 && humidity < 20) || (humidity > 60 && humidity <= 70)) { + percentValue -= 5; + } else if ((humidity >= 0 && humidity < 10) || (humidity > 70 && humidity <= 80)) { + percentValue -= 10; + } else if (humidity > 80) { + percentValue -= 20; + } + + // Air quality calculation + switch (airQuality) { + case "좋음": + percentValue += 10; + break; + case "보통": + percentValue += 5; + break; + case "나쁨": + percentValue -= 5; + break; + case "매우 나쁨": + percentValue -= 10; + break; + case "위험": + percentValue -= 20; + break; + default: + break; + } + + int uvIndex = Integer.parseInt(prepareDto.getUv()); // 자외선 지수 + if (uvIndex >= 0 && uvIndex <= 2) { + percentValue += 10; + } else if (uvIndex >= 3 && uvIndex <= 5) { + percentValue += 5; + } else if (uvIndex >= 6 && uvIndex <= 7) { + percentValue += 0; + } else if (uvIndex >= 8 && uvIndex <= 10) { + percentValue -= 5; + } else if (uvIndex >= 11) { + percentValue -= 10; + } + + percentValue = Math.max(0, Math.min(100, percentValue)); + } catch (NumberFormatException e) { + log.error("NumberFormatException occurred while parsing data: {}", e.getMessage()); + throw new BaseException(ResponseStatus.INVALID_DATA_FORMAT); } - // 강수 확률과 형태에 따른 우산 우선 여부를 판단하는 메서드 - private String needUmbrella(String pop, String pty) { - if (pop.equals("0") && pty.equals("0")) { - return "우산 필요 없음"; // 눈이나 비가 안옴 - } - else { - return "우산 필요"; // 눈이나 비가 옴 - } + return percentValue; + } + + private String airQualityScore(String pm10S, String pm25S) { + int pmScore = 0; + + if (pm10S != "null") { + int pm10 = Integer.parseInt(pm10S); + // PM10 점수 계산 + if (pm10 >= 0 && pm10 <= 30) { + pmScore += 10; + } else if (pm10 >= 31 && pm10 <= 80) { + pmScore += 0; + } else if (pm10 >= 81 && pm10 <= 150) { + pmScore -= 5; + } else if (pm10 >= 151) { + pmScore -= 10; + } } - public int getPercentValue(PrepareDto prepareDto) throws BaseException { - // 구현 방법에 따라 외출 적합도를 판단하여 해당 퍼센트 값을 반환 - int percentValue = 50; // 디폴트 값 0 - - try { - // 현재 실시간 weather 정보 - int temperature = Integer.parseInt(prepareDto.getTmp()); // 기온 - int precipitationProbability = Integer.parseInt(prepareDto.getPop()); // 강수확률 - int humidity = Integer.parseInt(prepareDto.getReh()); // 습도 - String airQuality = airQualityScore(prepareDto.getPm10grade(), prepareDto.getPm25grade()); // 대기질 등급 계산 - - // Temperature calculation - if (temperature >= 20 && temperature <= 25) { - percentValue += 10; - } else if ((temperature >= 15 && temperature < 20) || (temperature > 25 && temperature <= 30)) { - percentValue += 5; - } else if ((temperature >= 10 && temperature < 15) || (temperature > 30 && temperature <= 35)) { - percentValue -= 5; - } else if ((temperature >= 0 && temperature < 10) || (temperature > 35 && temperature <= 40)) { - percentValue -= 10; - } else if (temperature < 0 || temperature >= 40) { - percentValue -= 20; - } - - // Precipitation probability calculation - if (precipitationProbability <= 30) { - percentValue += 10; - } else if (precipitationProbability <= 50) { - percentValue += 5; - } else if (precipitationProbability <= 70) { - percentValue += 0; - } else if (precipitationProbability <= 80) { - percentValue -= 5; - } else if (precipitationProbability > 80) { - percentValue -= 10; - } - - // Humidity calculation - if (humidity >= 30 && humidity <= 50) { - percentValue += 10; - } else if ((humidity >= 20 && humidity < 30) || (humidity > 50 && humidity <= 60)) { - percentValue += 5; - } else if ((humidity >= 10 && humidity < 20) || (humidity > 60 && humidity <= 70)) { - percentValue -= 5; - } else if ((humidity >= 0 && humidity < 10) || (humidity > 70 && humidity <= 80)) { - percentValue -= 10; - } else if (humidity > 80) { - percentValue -= 20; - } - - // Air quality calculation - switch (airQuality) { - case "좋음": - percentValue += 10; - break; - case "보통": - percentValue += 5; - break; - case "나쁨": - percentValue -= 5; - break; - case "매우 나쁨": - percentValue -= 10; - break; - case "위험": - percentValue -= 20; - break; - default: - break; - } - - int uvIndex = Integer.parseInt(prepareDto.getUv()); // 자외선 지수 - if (uvIndex >= 0 && uvIndex <= 2) { - percentValue += 10; - } else if (uvIndex >= 3 && uvIndex <= 5) { - percentValue += 5; - } else if (uvIndex >= 6 && uvIndex <= 7) { - percentValue += 0; - } else if (uvIndex >= 8 && uvIndex <= 10) { - percentValue -= 5; - } else if (uvIndex >= 11) { - percentValue -= 10; - } - - percentValue = Math.max(0, Math.min(100, percentValue)); - } catch (NumberFormatException e) { - log.error("NumberFormatException occurred while parsing data: {}", e.getMessage()); - throw new BaseException(ResponseStatus.INVALID_DATA_FORMAT); - } - - return percentValue; + if (pm25S != "null") { + int pm25 = Integer.parseInt(pm25S); + // PM2.5 점수 계산 + if (pm25 >= 0 && pm25 <= 15) { + pmScore += 10; + } else if (pm25 >= 16 && pm25 <= 35) { + pmScore += 0; + } else if (pm25 >= 36 && pm25 <= 75) { + pmScore -= 5; + } else if (pm25 >= 76) { + pmScore -= 10; + } } - private String airQualityScore(String pm10S, String pm25S) { - int pmScore = 0; - - if (pm10S != "null") { - int pm10 = Integer.parseInt(pm10S); - // PM10 점수 계산 - if (pm10 >= 0 && pm10 <= 30) { - pmScore += 10; - } else if (pm10 >= 31 && pm10 <= 80) { - pmScore += 0; - } else if (pm10 >= 81 && pm10 <= 150) { - pmScore -= 5; - } else if (pm10 >= 151) { - pmScore -= 10; - } - } - - if (pm25S != "null") { - int pm25 = Integer.parseInt(pm25S); - // PM2.5 점수 계산 - if (pm25 >= 0 && pm25 <= 15) { - pmScore += 10; - } else if (pm25 >= 16 && pm25 <= 35) { - pmScore += 0; - } else if (pm25 >= 36 && pm25 <= 75) { - pmScore -= 5; - } else if (pm25 >= 76) { - pmScore -= 10; - } - } - - // 대기질 점수 계산 - String airQualityScore = ""; - - if (pmScore >= 10) { - airQualityScore = "좋음"; // 좋음 - } else if (pmScore >= 0) { - airQualityScore = "보통"; // 보통 - } else if (pmScore >= -5) { - airQualityScore = "나쁨"; // 나쁨 - } else if (pmScore >= -10) { - airQualityScore = "매우 나쁨"; // 매우 나쁨 - } else { - airQualityScore = "위험"; // 위험 - } - - return airQualityScore; + // 대기질 점수 계산 + String airQualityScore = ""; + + if (pmScore >= 10) { + airQualityScore = "좋음"; // 좋음 + } else if (pmScore >= 0) { + airQualityScore = "보통"; // 보통 + } else if (pmScore >= -5) { + airQualityScore = "나쁨"; // 나쁨 + } else if (pmScore >= -10) { + airQualityScore = "매우 나쁨"; // 매우 나쁨 + } else { + airQualityScore = "위험"; // 위험 } - public String getResultValue(int percent) { - if (percent >= 0 && percent <= 20) { - return "외출하기 매우 나쁜 날이에요! 가능하면 실내에서 활동하세요."; - } else if (percent <= 40) { - return "외출하기에는 조금 어려운 날씨에요. 외출 시에는 주의하세요."; - } else if (percent <= 60) { - return "외출하기 보통인 날씨에요. 잊은 물건은 없는지 확인하세요."; - } else if (percent <= 80) { - return "외출하기 좋은 날씨에요! 쾌적한 날씨를 즐기며 외출하세요."; - } else { - return "외출하기 아주 좋은 날씨에요! 좋은 날씨를 만끽해보세요."; - } + return airQualityScore; + } + + public String getResultValue(int percent) { + if (percent >= 0 && percent <= 20) { + return "외출하기 매우 나쁜 날이에요!"; + } else if (percent <= 40) { + return "외출하기에는 조금 어려운 날씨에요."; + } else if (percent <= 60) { + return "외출하기 보통인 날씨에요."; + } else if (percent <= 80) { + return "외출하기 좋은 날씨에요!"; + } else { + return "외출하기 아주 좋은 날씨에요!"; } + } } diff --git a/src/main/java/com/haemil/backend/weather/controller/AirController.java b/src/main/java/com/haemil/backend/weather/controller/AirController.java index e663b0f..849d50f 100644 --- a/src/main/java/com/haemil/backend/weather/controller/AirController.java +++ b/src/main/java/com/haemil/backend/weather/controller/AirController.java @@ -23,34 +23,34 @@ @RequiredArgsConstructor @RequestMapping("/air") public class AirController { - private final AirDto airdto; - private final AirService airService; + private final AirDto airdto; + private final AirService airService; - public List infoList = null; + public List infoList = null; - public TransferDto fetchDataAndProcess(HttpServletRequest request) throws BaseException { - String latitude = request.getParameter("latitude"); - String longitude = request.getParameter("longitude"); + public TransferDto fetchDataAndProcess(HttpServletRequest request) throws BaseException { + String latitude = request.getParameter("latitude"); + String longitude = request.getParameter("longitude"); - TransferDto transferDto = new TransferDto(); - transferDto.setX(latitude); - transferDto.setY(longitude); + TransferDto transferDto = new TransferDto(); + transferDto.setX(latitude); + transferDto.setY(longitude); - return transferDto; - } + return transferDto; + } - @GetMapping("/send") - public ResponseEntity sendGetRequest(HttpServletRequest request) { - try { - TransferDto transferDto = fetchDataAndProcess(request); - String jsonString = airService.getAirInfo(airdto, transferDto); + @GetMapping("/send") + public ResponseEntity sendGetRequest(HttpServletRequest request) { + try { + TransferDto transferDto = fetchDataAndProcess(request); + String jsonString = airService.getAirInfo(airdto, transferDto); - airService.isJson(jsonString); + airService.isJson(jsonString); - infoList = airService.ParsingJson(jsonString); - return new BaseResponse<>(infoList).convert(); - } catch (BaseException e) { - return new BaseResponse<>(e.getStatus()).convert(); - } + infoList = airService.ParsingJson(jsonString); + return new BaseResponse<>(infoList).convert(); + } catch (BaseException e) { + return new BaseResponse<>(e.getStatus()).convert(); } + } } diff --git a/src/main/java/com/haemil/backend/weather/controller/LivingController.java b/src/main/java/com/haemil/backend/weather/controller/LivingController.java index 766848f..125cd32 100644 --- a/src/main/java/com/haemil/backend/weather/controller/LivingController.java +++ b/src/main/java/com/haemil/backend/weather/controller/LivingController.java @@ -4,7 +4,6 @@ import com.haemil.backend.global.config.BaseResponse; import com.haemil.backend.weather.dto.*; import com.haemil.backend.weather.service.LivingService; -import com.haemil.backend.weather.service.WeatherService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.ResponseEntity; @@ -22,48 +21,43 @@ @RequiredArgsConstructor @RequestMapping("/living") public class LivingController { - private final LivingService livingService; - public List infoList = null; + private final LivingService livingService; + public List infoList = null; -// public LocationDto locationDto; + private LivingDto fetchDataAndProcess(HttpServletRequest request) throws BaseException { + String latitude = request.getParameter("latitude"); + String longitude = request.getParameter("longitude"); - private LivingDto fetchDataAndProcess(HttpServletRequest request) throws BaseException { - String latitude = request.getParameter("latitude"); - String longitude = request.getParameter("longitude"); + double lat = Double.parseDouble(latitude); + double lon = Double.parseDouble(longitude); - double lat = Double.parseDouble(latitude); - double lon = Double.parseDouble(longitude); + latitude = String.format("%.0f", lat); + longitude = String.format("%.0f", lon); - latitude = String.format("%.0f", lat); - longitude = String.format("%.0f", lon); + LivingDto livingDto = new LivingDto(); + livingDto.setLon(longitude); + livingDto.setLat(latitude); - LivingDto livingDto = new LivingDto(); - livingDto.setLon(longitude); - livingDto.setLat(latitude); + return livingDto; + } - return livingDto; - } - - @GetMapping("/send") - public ResponseEntity sendGetRequest(HttpServletRequest request) { - try { -// this.locationDto = locationDto; - LivingDto livingDto = fetchDataAndProcess(request); + @GetMapping("/send") + public ResponseEntity sendGetRequest(HttpServletRequest request) { + try { + LivingDto livingDto = fetchDataAndProcess(request); - // feel like temp - String jsonString1 = livingService.getLivingTempInfo(livingDto); -// log.debug("jsonString : " + jsonString1); - livingService.isJson(jsonString1); + // feel like temp + String jsonString1 = livingService.getLivingTempInfo(livingDto); + livingService.isJson(jsonString1); - // uv - String jsonString2 = livingService.getUVInfo(livingDto, request); -// log.debug("jsonString : " + jsonString2); - livingService.isJson(jsonString2); + // uv + String jsonString2 = livingService.getUVInfo(livingDto, request); + livingService.isJson(jsonString2); - infoList = livingService.ParsingJson(jsonString1, jsonString2); // 전체 리스트 - return new BaseResponse<>(infoList).convert(); - } catch (BaseException e) { - return new BaseResponse<>(e.getStatus()).convert(); - } + infoList = livingService.ParsingJson(jsonString1, jsonString2); // 전체 리스트 + return new BaseResponse<>(infoList).convert(); + } catch (BaseException e) { + return new BaseResponse<>(e.getStatus()).convert(); } + } } diff --git a/src/main/java/com/haemil/backend/weather/controller/WeatherController.java b/src/main/java/com/haemil/backend/weather/controller/WeatherController.java index 9206059..2b8c2af 100644 --- a/src/main/java/com/haemil/backend/weather/controller/WeatherController.java +++ b/src/main/java/com/haemil/backend/weather/controller/WeatherController.java @@ -25,118 +25,118 @@ @RequiredArgsConstructor @RequestMapping("/weather") public class WeatherController { - private final WeatherService weatherService; + private final WeatherService weatherService; - public Map transformedData; - public List currentTimeData; + public Map transformedData; + public List currentTimeData; - private WeatherDto fetchDataAndProcess(HttpServletRequest request) throws BaseException { - String latitude = request.getParameter("latitude"); - String longitude = request.getParameter("longitude"); + private WeatherDto fetchDataAndProcess(HttpServletRequest request) throws BaseException { + String latitude = request.getParameter("latitude"); + String longitude = request.getParameter("longitude"); - double lat = Double.parseDouble(latitude); - double lon = Double.parseDouble(longitude); + double lat = Double.parseDouble(latitude); + double lon = Double.parseDouble(longitude); - latitude = String.format("%.0f", lat); - longitude = String.format("%.0f", lon); + latitude = String.format("%.0f", lat); + longitude = String.format("%.0f", lon); - WeatherDto weatherDto = new WeatherDto(); - weatherDto.setNx(latitude); - weatherDto.setNy(longitude); + WeatherDto weatherDto = new WeatherDto(); + weatherDto.setNx(latitude); + weatherDto.setNy(longitude); - return weatherDto; - } + return weatherDto; + } + + @GetMapping("/today") + public ResponseEntity getTodayWeather(HttpServletRequest request) { // 오늘 현재 시간대 + try { + WeatherDto weatherDto = fetchDataAndProcess(request); - @GetMapping("/today") - public ResponseEntity getTodayWeather(HttpServletRequest request) { // 오늘 현재 시간대 - try { - WeatherDto weatherDto = fetchDataAndProcess(request); - - String jsonString = weatherService.getWeatherInfo(weatherDto); - weatherService.isJson(jsonString); - List infoList = weatherService.ParsingJson(jsonString); - List todayData = weatherService.filterCurrentTimeData(infoList, weatherDto); - return new BaseResponse<>(todayData).convert(); - } catch (BaseException e) { - return new BaseResponse<>(e.getStatus()).convert(); - } + String jsonString = weatherService.getWeatherInfo(weatherDto); + weatherService.isJson(jsonString); + List infoList = weatherService.ParsingJson(jsonString); + List todayData = weatherService.filterCurrentTimeData(infoList, weatherDto); + return new BaseResponse<>(todayData).convert(); + } catch (BaseException e) { + return new BaseResponse<>(e.getStatus()).convert(); } + } - @GetMapping("/send") - public ResponseEntity sendGetRequest(HttpServletRequest request) { // 모든 날씨 정보 - try { - WeatherDto weatherDto = fetchDataAndProcess(request); + @GetMapping("/send") + public ResponseEntity sendGetRequest(HttpServletRequest request) { // 모든 날씨 정보 + try { + WeatherDto weatherDto = fetchDataAndProcess(request); - String jsonString = weatherService.getWeatherInfo(weatherDto); - weatherService.isJson(jsonString); - List infoList = weatherService.ParsingJson(jsonString); + String jsonString = weatherService.getWeatherInfo(weatherDto); + weatherService.isJson(jsonString); + List infoList = weatherService.ParsingJson(jsonString); - currentTimeData = weatherService.filterCurrentTimeData(infoList, weatherDto); - transformedData = weatherService.transformWeatherData(infoList, currentTimeData, weatherDto); + currentTimeData = weatherService.filterCurrentTimeData(infoList, weatherDto); + transformedData = weatherService.transformWeatherData(infoList, currentTimeData, weatherDto); - return new BaseResponse<>(infoList).convert(); - } catch (BaseException e) { - return new BaseResponse<>(e.getStatus()).convert(); - } + return new BaseResponse<>(infoList).convert(); + } catch (BaseException e) { + return new BaseResponse<>(e.getStatus()).convert(); } + } - @GetMapping("/data") - public ResponseEntity getTMNandTMXData(HttpServletRequest request) { - try { - WeatherDto weatherDto = fetchDataAndProcess(request); + @GetMapping("/data") + public ResponseEntity getTMNandTMXData(HttpServletRequest request) { + try { + WeatherDto weatherDto = fetchDataAndProcess(request); - String jsonString = weatherService.getWeatherInfo(weatherDto); - weatherService.isJson(jsonString); - List infoList = weatherService.ParsingJson(jsonString); - List todayData = weatherService.filterCurrentTimeData(infoList, weatherDto); + String jsonString = weatherService.getWeatherInfo(weatherDto); + weatherService.isJson(jsonString); + List infoList = weatherService.ParsingJson(jsonString); + List todayData = weatherService.filterCurrentTimeData(infoList, weatherDto); - transformedData = weatherService.transformWeatherData(infoList, todayData, weatherDto); + transformedData = weatherService.transformWeatherData(infoList, todayData, weatherDto); - return new BaseResponse<>(transformedData).convert(); - } catch (BaseException e) { - return new BaseResponse<>(e.getStatus()).convert(); - } + return new BaseResponse<>(transformedData).convert(); + } catch (BaseException e) { + return new BaseResponse<>(e.getStatus()).convert(); } - - @GetMapping("/tmps") - public ResponseEntity getTemperatures(HttpServletRequest request) { // 3일치 온도&하늘상태 가져오기 - try { - WeatherDto weatherDto = fetchDataAndProcess(request); - - String jsonString = weatherService.getWeatherInfo(weatherDto); - weatherService.isJson(jsonString); - List infoList = weatherService.ParsingJson(jsonString); - List> temperatureData = weatherService.filterCurrentTimeAndSpecifiedDateData(infoList, "1500"); - - return new BaseResponse<>(temperatureData).convert(); - } catch (BaseException e) { - return new BaseResponse<>(e.getStatus()).convert(); - } + } + + @GetMapping("/tmps") + public ResponseEntity getTemperatures( + HttpServletRequest request) { // 3일치 온도&하늘상태 가져오기 + try { + WeatherDto weatherDto = fetchDataAndProcess(request); + + String jsonString = weatherService.getWeatherInfo(weatherDto); + weatherService.isJson(jsonString); + List infoList = weatherService.ParsingJson(jsonString); + List> temperatureData = + weatherService.filterCurrentTimeAndSpecifiedDateData(infoList, "1500"); + + return new BaseResponse<>(temperatureData).convert(); + } catch (BaseException e) { + return new BaseResponse<>(e.getStatus()).convert(); } + } - @GetMapping("/times") - public ResponseEntity getNextHoursWeather(HttpServletRequest request) { // 시간대별 온도&하늘상태 가져오기 - try { - WeatherDto weatherDto = fetchDataAndProcess(request); + @GetMapping("/times") + public ResponseEntity getNextHoursWeather( + HttpServletRequest request) { // 시간대별 온도&하늘상태 가져오기 + try { + WeatherDto weatherDto = fetchDataAndProcess(request); - String jsonString = weatherService.getWeatherInfo(weatherDto); - weatherService.isJson(jsonString); - List infoList = weatherService.ParsingJson(jsonString); + String jsonString = weatherService.getWeatherInfo(weatherDto); + weatherService.isJson(jsonString); + List infoList = weatherService.ParsingJson(jsonString); - // 현재 날짜를 기준으로 시작 시간 설정 - LocalDate currentDate = LocalDate.now(); - LocalTime startTime = LocalTime.of(8, 0); // 시작 시간을 8시로 설정 + // 현재 날짜를 기준으로 시작 시간 설정 + LocalDate currentDate = LocalDate.now(); + LocalTime startTime = LocalTime.of(8, 0); // 시작 시간을 8시로 설정 - // 오늘의 데이터를 가져오도록 설정 - List> filteredData = weatherService.filterNextData(infoList, startTime, 15); + // 오늘의 데이터를 가져오도록 설정 + List> filteredData = + weatherService.filterNextData(infoList, startTime, 15); - return new BaseResponse<>(filteredData).convert(); - } catch (BaseException e) { - return new BaseResponse<>(e.getStatus()).convert(); - } + return new BaseResponse<>(filteredData).convert(); + } catch (BaseException e) { + return new BaseResponse<>(e.getStatus()).convert(); } - - - + } } - diff --git a/src/main/java/com/haemil/backend/weather/dto/AirDto.java b/src/main/java/com/haemil/backend/weather/dto/AirDto.java index e15921b..e227525 100644 --- a/src/main/java/com/haemil/backend/weather/dto/AirDto.java +++ b/src/main/java/com/haemil/backend/weather/dto/AirDto.java @@ -6,11 +6,12 @@ @Data @Component public class AirDto { - private final String apiUrl = "http://apis.data.go.kr/B552584/ArpltnInforInqireSvc/getMsrstnAcctoRltmMesureDnsty"; // 측정소별 실시간 측정정보 조회 - private final String numOfRows = "10"; - private final String pageNo = "1"; - private final String returnType = "json"; - private String stationName; // 측정소 명 - private final String dataTerm = "DAILY"; - private final String ver = "1.0"; + private final String apiUrl = + "http://apis.data.go.kr/B552584/ArpltnInforInqireSvc/getMsrstnAcctoRltmMesureDnsty"; + private final String numOfRows = "10"; + private final String pageNo = "1"; + private final String returnType = "json"; + private String stationName; // 측정소 명 + private final String dataTerm = "DAILY"; + private final String ver = "1.0"; } diff --git a/src/main/java/com/haemil/backend/weather/dto/AirInfoDto.java b/src/main/java/com/haemil/backend/weather/dto/AirInfoDto.java index f7733d2..12b5406 100644 --- a/src/main/java/com/haemil/backend/weather/dto/AirInfoDto.java +++ b/src/main/java/com/haemil/backend/weather/dto/AirInfoDto.java @@ -4,9 +4,9 @@ @Data public class AirInfoDto { - private String dataTime; // 측정일 - private String pm10Value; // 미세먼지 농도 - private String pm25Value; // 초미세먼지 농도 - private String pm10Grade; // 미세먼지 24시간 등급 - private String pm25Grade; // 초미세먼지 농도 + private String dataTime; // 측정일 + private String pm10Value; // 미세먼지 농도 + private String pm25Value; // 초미세먼지 농도 + private String pm10Grade; // 미세먼지 24시간 등급 + private String pm25Grade; // 초미세먼지 농도 } diff --git a/src/main/java/com/haemil/backend/weather/dto/LivingDto.java b/src/main/java/com/haemil/backend/weather/dto/LivingDto.java index 1c4dadb..15d1faa 100644 --- a/src/main/java/com/haemil/backend/weather/dto/LivingDto.java +++ b/src/main/java/com/haemil/backend/weather/dto/LivingDto.java @@ -8,24 +8,25 @@ @Data @Component public class LivingDto { - // 체감 온도 - private final String apiUrl = "https://api.openweathermap.org/data/2.5/weather"; - private String lat; - private String lon; - private final String lang = "kr"; - private final String units = "metric"; + // 체감 온도 + private final String apiUrl = "https://api.openweathermap.org/data/2.5/weather"; + private String lat; + private String lon; + private final String lang = "kr"; + private final String units = "metric"; - // 자외선 - private final String apiUrlUV = "http://apis.data.go.kr/1360000/LivingWthrIdxServiceV4/getUVIdxV4"; - private String areaNo; // 행정 구역 코드 - private final String numOfRows = "10"; - private final String pageNo = "1"; - private final String dataType = "json"; - private final String time = generateFormattedTime(); // 현재 시간으로 변경 + // 자외선 + private final String apiUrlUV = + "http://apis.data.go.kr/1360000/LivingWthrIdxServiceV4/getUVIdxV4"; + private String areaNo; // 행정 구역 코드 + private final String numOfRows = "10"; + private final String pageNo = "1"; + private final String dataType = "json"; + private final String time = generateFormattedTime(); // 현재 시간으로 변경 - private String generateFormattedTime() { - LocalDateTime now = LocalDateTime.now(); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHH"); - return now.format(formatter); - } + private String generateFormattedTime() { + LocalDateTime now = LocalDateTime.now(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHH"); + return now.format(formatter); + } } diff --git a/src/main/java/com/haemil/backend/weather/dto/LivingInfoDto.java b/src/main/java/com/haemil/backend/weather/dto/LivingInfoDto.java index 7de96c0..758c14f 100644 --- a/src/main/java/com/haemil/backend/weather/dto/LivingInfoDto.java +++ b/src/main/java/com/haemil/backend/weather/dto/LivingInfoDto.java @@ -6,6 +6,6 @@ @Data @Component public class LivingInfoDto { - private String feels_like; // 체감 온도 - private String uvi; // 자외선 수치 + private String feels_like; // 체감 온도 + private String uvi; // 자외선 수치 } diff --git a/src/main/java/com/haemil/backend/weather/dto/StationDto.java b/src/main/java/com/haemil/backend/weather/dto/StationDto.java index 35a73bf..1df0211 100644 --- a/src/main/java/com/haemil/backend/weather/dto/StationDto.java +++ b/src/main/java/com/haemil/backend/weather/dto/StationDto.java @@ -1,14 +1,15 @@ package com.haemil.backend.weather.dto; + import lombok.Data; import org.springframework.stereotype.Component; @Data @Component public class StationDto { - private final String apiUrl = "http://apis.data.go.kr/B552584/MsrstnInfoInqireSvc/getNearbyMsrstnList"; // 근접측정소 목록 조회 상세기능명세 - private final String returnType = "json"; + private final String apiUrl = + "http://apis.data.go.kr/B552584/MsrstnInfoInqireSvc/getNearbyMsrstnList"; + private final String returnType = "json"; - private String tmX; - private String tmY; + private String tmX; + private String tmY; } - diff --git a/src/main/java/com/haemil/backend/weather/dto/StationInfoDto.java b/src/main/java/com/haemil/backend/weather/dto/StationInfoDto.java index 16f8af5..3bc357e 100644 --- a/src/main/java/com/haemil/backend/weather/dto/StationInfoDto.java +++ b/src/main/java/com/haemil/backend/weather/dto/StationInfoDto.java @@ -4,5 +4,5 @@ @Data public class StationInfoDto { - public String stationName; // 측정소명 + public String stationName; // 측정소명 } diff --git a/src/main/java/com/haemil/backend/weather/dto/TransferDto.java b/src/main/java/com/haemil/backend/weather/dto/TransferDto.java index cc1fa2e..b8bd6d5 100644 --- a/src/main/java/com/haemil/backend/weather/dto/TransferDto.java +++ b/src/main/java/com/haemil/backend/weather/dto/TransferDto.java @@ -6,6 +6,6 @@ @Data @Component public class TransferDto { - private String x; - private String y; + private String x; + private String y; } diff --git a/src/main/java/com/haemil/backend/weather/dto/WeatherDto.java b/src/main/java/com/haemil/backend/weather/dto/WeatherDto.java index cfd9dc2..49b1f47 100644 --- a/src/main/java/com/haemil/backend/weather/dto/WeatherDto.java +++ b/src/main/java/com/haemil/backend/weather/dto/WeatherDto.java @@ -10,27 +10,28 @@ @Data @Component public class WeatherDto { - private final String apiUrl = "http://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilageFcst"; // 단기예보 - private final String numOfRows = "2000"; - private final String pageNo = "1"; - private final String dataType = "json"; + private final String apiUrl = + "http://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilageFcst"; // 단기예보 + private final String numOfRows = "2000"; + private final String pageNo = "1"; + private final String dataType = "json"; - private final String base_date; - private final String base_time = "0200"; - private final String current_time; - private String nx; - private String ny; + private final String base_date; + private final String base_time = "0200"; + private final String current_time; + private String nx; + private String ny; - public WeatherDto() { - LocalDate today = LocalDate.now(); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd"); - this.base_date = today.format(formatter); + public WeatherDto() { + LocalDate today = LocalDate.now(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd"); + this.base_date = today.format(formatter); - // current_time - 지금 시 : ex) 12:30 -> 1200 - LocalTime currentTime = LocalTime.now(); - DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH"); - String formattedTime = currentTime.format(timeFormatter); + // current_time - 지금 시 : ex) 12:30 -> 1200 + LocalTime currentTime = LocalTime.now(); + DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH"); + String formattedTime = currentTime.format(timeFormatter); - this.current_time = formattedTime + "00"; - } + this.current_time = formattedTime + "00"; + } } diff --git a/src/main/java/com/haemil/backend/weather/dto/WeatherInfoDto.java b/src/main/java/com/haemil/backend/weather/dto/WeatherInfoDto.java index 994a02c..58ae56e 100644 --- a/src/main/java/com/haemil/backend/weather/dto/WeatherInfoDto.java +++ b/src/main/java/com/haemil/backend/weather/dto/WeatherInfoDto.java @@ -1,10 +1,11 @@ package com.haemil.backend.weather.dto; + import lombok.Data; @Data public class WeatherInfoDto { - private String fcstDate; // 예측일자 - private String fcstTime; // 예측시간 - private String category; // 자료구분문자 - private String fcstValue; // 예보값 + private String fcstDate; // 예측일자 + private String fcstTime; // 예측시간 + private String category; // 자료구분문자 + private String fcstValue; // 예보값 } diff --git a/src/main/java/com/haemil/backend/weather/service/AirService.java b/src/main/java/com/haemil/backend/weather/service/AirService.java index 61fc3b4..a8fbae1 100644 --- a/src/main/java/com/haemil/backend/weather/service/AirService.java +++ b/src/main/java/com/haemil/backend/weather/service/AirService.java @@ -15,7 +15,6 @@ import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; -import javax.servlet.http.HttpServletRequest; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; @@ -25,90 +24,99 @@ @Service @RequiredArgsConstructor public class AirService { - private final RestTemplate restTemplate; - private final StationService stationService; - @Value("${api.hj-secret-key}") - String serviceKey; - - public String getAirInfo(AirDto airDto, TransferDto transferDto) throws BaseException { - String responseBody; - try { - String apiUrl = airDto.getApiUrl(); - String returnType = airDto.getReturnType(); - String numOfRows = airDto.getNumOfRows(); - String pageNo = airDto.getPageNo(); - String stationName = stationService.getStationName(stationService.getStationInfo(transferDto)); -// log.info("air - stationName = {}", stationName); - String dataTerm = airDto.getDataTerm(); - String ver = airDto.getVer(); - -// log.debug("stationName: " + stationName); - - StringBuilder urlBuilder = new StringBuilder(apiUrl); - urlBuilder.append("?"+ URLEncoder.encode("serviceKey", "UTF-8")+"="+serviceKey); - urlBuilder.append("&"+ URLEncoder.encode("returnType", "UTF-8")+"="+URLEncoder.encode(returnType, "UTF-8")); - urlBuilder.append("&"+ URLEncoder.encode("numOfRows", "UTF-8")+"="+URLEncoder.encode(numOfRows, "UTF-8")); - urlBuilder.append("&"+ URLEncoder.encode("pageNo", "UTF-8")+"="+URLEncoder.encode(pageNo, "UTF-8")); - urlBuilder.append("&"+ URLEncoder.encode("stationName", "UTF-8")+"="+stationName); - urlBuilder.append("&"+ URLEncoder.encode("dataTerm", "UTF-8")+"="+URLEncoder.encode(dataTerm, "UTF-8")); - urlBuilder.append("&"+ URLEncoder.encode("ver", "UTF-8")+"="+URLEncoder.encode(ver, "UTF-8")); - - ResponseEntity response = restTemplate.getForEntity(urlBuilder.toString(), String.class); - - responseBody = response.getBody(); - -// log.info("Air _ urlBuilder: " + urlBuilder); -// log.info("Air _ responseBody: " + responseBody); - } catch (UnsupportedEncodingException e) { - log.debug("UnsupportedEncodingException 발생 "); - throw new BaseException(ResponseStatus.UNSUPPORTED_ENCODING); - } - return responseBody; + private final RestTemplate restTemplate; + private final StationService stationService; + + @Value("${api.hj-secret-key}") + String serviceKey; + + public String getAirInfo(AirDto airDto, TransferDto transferDto) throws BaseException { + String responseBody; + try { + String apiUrl = airDto.getApiUrl(); + String returnType = airDto.getReturnType(); + String numOfRows = airDto.getNumOfRows(); + String pageNo = airDto.getPageNo(); + String stationName = + stationService.getStationName(stationService.getStationInfo(transferDto)); + String dataTerm = airDto.getDataTerm(); + String ver = airDto.getVer(); + + StringBuilder urlBuilder = new StringBuilder(apiUrl); + urlBuilder.append("?" + URLEncoder.encode("serviceKey", "UTF-8") + "=" + serviceKey); + urlBuilder.append( + "&" + + URLEncoder.encode("returnType", "UTF-8") + + "=" + + URLEncoder.encode(returnType, "UTF-8")); + urlBuilder.append( + "&" + + URLEncoder.encode("numOfRows", "UTF-8") + + "=" + + URLEncoder.encode(numOfRows, "UTF-8")); + urlBuilder.append( + "&" + URLEncoder.encode("pageNo", "UTF-8") + "=" + URLEncoder.encode(pageNo, "UTF-8")); + urlBuilder.append("&" + URLEncoder.encode("stationName", "UTF-8") + "=" + stationName); + urlBuilder.append( + "&" + + URLEncoder.encode("dataTerm", "UTF-8") + + "=" + + URLEncoder.encode(dataTerm, "UTF-8")); + urlBuilder.append( + "&" + URLEncoder.encode("ver", "UTF-8") + "=" + URLEncoder.encode(ver, "UTF-8")); + + ResponseEntity response = + restTemplate.getForEntity(urlBuilder.toString(), String.class); + + responseBody = response.getBody(); + + } catch (UnsupportedEncodingException e) { + log.debug("UnsupportedEncodingException 발생 "); + throw new BaseException(ResponseStatus.UNSUPPORTED_ENCODING); } - - public List ParsingJson(String responseBody) throws BaseException { - List airInfoDtoList; - try { - ObjectMapper objectMapper = new ObjectMapper(); - - JsonNode jsonNode = objectMapper.readTree(responseBody); -// log.info("jsonNode = {}", jsonNode); - JsonNode itemsNode = jsonNode.get("response").get("body").get("items"); -// log.info("itemsNode = {}", itemsNode); - - airInfoDtoList = new ArrayList<>(); - if (itemsNode.isArray()) { - for (JsonNode node : itemsNode) { - String dataTime = node.get("dataTime").asText(); - String pm10Value = node.get("pm10Value").asText(); - String pm25Value = node.get("pm25Value").asText(); - String pm10Grade = node.get("pm10Grade").asText(); - String pm25Grade = node.get("pm25Grade").asText(); - - AirInfoDto airInfoDto = new AirInfoDto(); - airInfoDto.setDataTime(dataTime); - airInfoDto.setPm10Value(pm10Value); - airInfoDto.setPm10Grade(pm10Grade); - airInfoDto.setPm25Grade(pm25Grade); - airInfoDto.setPm25Value(pm25Value); - airInfoDtoList.add(airInfoDto); - } - } - -// log.debug("airInfoDtoList:" + airInfoDtoList); - return airInfoDtoList; - } catch (JsonProcessingException e) { - throw new BaseException(ResponseStatus.CANNOT_CONVERT_JSON); + return responseBody; + } + + public List ParsingJson(String responseBody) throws BaseException { + List airInfoDtoList; + try { + ObjectMapper objectMapper = new ObjectMapper(); + + JsonNode jsonNode = objectMapper.readTree(responseBody); + JsonNode itemsNode = jsonNode.get("response").get("body").get("items"); + + airInfoDtoList = new ArrayList<>(); + if (itemsNode.isArray()) { + for (JsonNode node : itemsNode) { + String dataTime = node.get("dataTime").asText(); + String pm10Value = node.get("pm10Value").asText(); + String pm25Value = node.get("pm25Value").asText(); + String pm10Grade = node.get("pm10Grade").asText(); + String pm25Grade = node.get("pm25Grade").asText(); + + AirInfoDto airInfoDto = new AirInfoDto(); + airInfoDto.setDataTime(dataTime); + airInfoDto.setPm10Value(pm10Value); + airInfoDto.setPm10Grade(pm10Grade); + airInfoDto.setPm25Grade(pm25Grade); + airInfoDto.setPm25Value(pm25Value); + airInfoDtoList.add(airInfoDto); } + } + + return airInfoDtoList; + } catch (JsonProcessingException e) { + throw new BaseException(ResponseStatus.CANNOT_CONVERT_JSON); } + } - public boolean isJson(String jsonString) throws BaseException { - boolean isJson = jsonString.startsWith("{") && jsonString.endsWith("}"); + public boolean isJson(String jsonString) throws BaseException { + boolean isJson = jsonString.startsWith("{") && jsonString.endsWith("}"); - if (!isJson) { - throw new BaseException(ResponseStatus.INVALID_XML_FORMAT); - } else { - return true; - } + if (!isJson) { + throw new BaseException(ResponseStatus.INVALID_XML_FORMAT); + } else { + return true; } + } } diff --git a/src/main/java/com/haemil/backend/weather/service/LivingService.java b/src/main/java/com/haemil/backend/weather/service/LivingService.java index e980e82..a848f2b 100644 --- a/src/main/java/com/haemil/backend/weather/service/LivingService.java +++ b/src/main/java/com/haemil/backend/weather/service/LivingService.java @@ -3,11 +3,8 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import com.haemil.backend.alert.dto.ReqCoordDto; import com.haemil.backend.global.config.BaseException; import com.haemil.backend.global.config.ResponseStatus; -import com.haemil.backend.weather.dto.AirDto; -import com.haemil.backend.weather.dto.AirInfoDto; import com.haemil.backend.weather.dto.LivingDto; import com.haemil.backend.weather.dto.LivingInfoDto; import lombok.RequiredArgsConstructor; @@ -27,123 +24,136 @@ @Service @RequiredArgsConstructor public class LivingService { - private final RestTemplate restTemplate; - @Value("${api.hj-openweather-key}") - String serviceKey; - - @Value("${api.hj-secret-key}") - String serviceKey2; - - // 체감 온도 - public String getLivingTempInfo(LivingDto livingDto) throws BaseException { - String responseBody; - try { - String apiUrl = livingDto.getApiUrl(); - String lat = livingDto.getLat(); - String lon = livingDto.getLon(); - String lang = livingDto.getLang(); - String units = livingDto.getUnits(); - - StringBuilder urlBuilder = new StringBuilder(apiUrl); - urlBuilder.append("?"+ URLEncoder.encode("appid", "UTF-8")+"="+serviceKey); - urlBuilder.append("&"+ URLEncoder.encode("lat", "UTF-8")+"="+URLEncoder.encode(lat, "UTF-8")); - urlBuilder.append("&"+ URLEncoder.encode("lon", "UTF-8")+"="+URLEncoder.encode(lon, "UTF-8")); - urlBuilder.append("&"+ URLEncoder.encode("lang", "UTF-8")+"="+URLEncoder.encode(lang, "UTF-8")); - urlBuilder.append("&"+ URLEncoder.encode("units", "UTF-8")+"="+URLEncoder.encode(units, "UTF-8")); - - ResponseEntity response = restTemplate.getForEntity(urlBuilder.toString(), String.class); - - responseBody = response.getBody(); - - } catch (UnsupportedEncodingException e) { - log.debug("UnsupportedEncodingException 발생 "); - throw new BaseException(ResponseStatus.UNSUPPORTED_ENCODING); - } - return responseBody; + private final RestTemplate restTemplate; + + @Value("${api.hj-openweather-key}") + String serviceKey; + + @Value("${api.hj-secret-key}") + String serviceKey2; + + // 체감 온도 + public String getLivingTempInfo(LivingDto livingDto) throws BaseException { + String responseBody; + try { + String apiUrl = livingDto.getApiUrl(); + String lat = livingDto.getLat(); + String lon = livingDto.getLon(); + String lang = livingDto.getLang(); + String units = livingDto.getUnits(); + + StringBuilder urlBuilder = new StringBuilder(apiUrl); + urlBuilder.append("?" + URLEncoder.encode("appid", "UTF-8") + "=" + serviceKey); + urlBuilder.append( + "&" + URLEncoder.encode("lat", "UTF-8") + "=" + URLEncoder.encode(lat, "UTF-8")); + urlBuilder.append( + "&" + URLEncoder.encode("lon", "UTF-8") + "=" + URLEncoder.encode(lon, "UTF-8")); + urlBuilder.append( + "&" + URLEncoder.encode("lang", "UTF-8") + "=" + URLEncoder.encode(lang, "UTF-8")); + urlBuilder.append( + "&" + URLEncoder.encode("units", "UTF-8") + "=" + URLEncoder.encode(units, "UTF-8")); + + ResponseEntity response = + restTemplate.getForEntity(urlBuilder.toString(), String.class); + + responseBody = response.getBody(); + + } catch (UnsupportedEncodingException e) { + log.debug("UnsupportedEncodingException 발생 "); + throw new BaseException(ResponseStatus.UNSUPPORTED_ENCODING); } - - private final LocationService locationService; - // 자외선 - public String getUVInfo(LivingDto livingDto, HttpServletRequest request) throws BaseException { - String responseBody; - try { - String apiUrl = livingDto.getApiUrlUV(); - String dataType = livingDto.getDataType(); - String areaNo = locationService.getLocation(locationService.getLocationInfo(request)).getAreaNo(); - - if (areaNo.length() >= 2) { - String modifiedAreaNo = areaNo.substring(0, areaNo.length() - 5) + "00000"; -// locationService.getLocation(locationService.getLocationInfo(request)).setAreaNo(modifiedAreaNo); - areaNo = modifiedAreaNo; - } - String numOfRows = livingDto.getNumOfRows(); - String pageNo = livingDto.getPageNo(); - String time = livingDto.getTime(); - - StringBuilder urlBuilder = new StringBuilder(apiUrl); - urlBuilder.append("?"+ URLEncoder.encode("serviceKey", "UTF-8")+"="+serviceKey2); - urlBuilder.append("&"+ URLEncoder.encode("dataType", "UTF-8")+"="+URLEncoder.encode(dataType, "UTF-8")); - urlBuilder.append("&"+ URLEncoder.encode("areaNo", "UTF-8")+"="+URLEncoder.encode(areaNo, "UTF-8")); - urlBuilder.append("&"+ URLEncoder.encode("numOfRows", "UTF-8")+"="+URLEncoder.encode(numOfRows, "UTF-8")); - urlBuilder.append("&"+ URLEncoder.encode("pageNo", "UTF-8")+"="+URLEncoder.encode(pageNo, "UTF-8")); - urlBuilder.append("&"+ URLEncoder.encode("time", "UTF-8")+"="+URLEncoder.encode(time, "UTF-8")); - - ResponseEntity response = restTemplate.getForEntity(urlBuilder.toString(), String.class); - - responseBody = response.getBody(); - } catch (UnsupportedEncodingException e) { - log.debug("UnsupportedEncodingException 발생 "); - throw new BaseException(ResponseStatus.UNSUPPORTED_ENCODING); - } - return responseBody; + return responseBody; + } + + private final LocationService locationService; + + // 자외선 + public String getUVInfo(LivingDto livingDto, HttpServletRequest request) throws BaseException { + String responseBody; + try { + String apiUrl = livingDto.getApiUrlUV(); + String dataType = livingDto.getDataType(); + String areaNo = + locationService.getLocation(locationService.getLocationInfo(request)).getAreaNo(); + + if (areaNo.length() >= 2) { + String modifiedAreaNo = areaNo.substring(0, areaNo.length() - 5) + "00000"; + areaNo = modifiedAreaNo; + } + String numOfRows = livingDto.getNumOfRows(); + String pageNo = livingDto.getPageNo(); + String time = livingDto.getTime(); + + StringBuilder urlBuilder = new StringBuilder(apiUrl); + urlBuilder.append("?" + URLEncoder.encode("serviceKey", "UTF-8") + "=" + serviceKey2); + urlBuilder.append( + "&" + + URLEncoder.encode("dataType", "UTF-8") + + "=" + + URLEncoder.encode(dataType, "UTF-8")); + urlBuilder.append( + "&" + URLEncoder.encode("areaNo", "UTF-8") + "=" + URLEncoder.encode(areaNo, "UTF-8")); + urlBuilder.append( + "&" + + URLEncoder.encode("numOfRows", "UTF-8") + + "=" + + URLEncoder.encode(numOfRows, "UTF-8")); + urlBuilder.append( + "&" + URLEncoder.encode("pageNo", "UTF-8") + "=" + URLEncoder.encode(pageNo, "UTF-8")); + urlBuilder.append( + "&" + URLEncoder.encode("time", "UTF-8") + "=" + URLEncoder.encode(time, "UTF-8")); + + ResponseEntity response = + restTemplate.getForEntity(urlBuilder.toString(), String.class); + + responseBody = response.getBody(); + } catch (UnsupportedEncodingException e) { + log.debug("UnsupportedEncodingException 발생 "); + throw new BaseException(ResponseStatus.UNSUPPORTED_ENCODING); } - - public List ParsingJson(String responseBody1, String responseBody2) throws BaseException { - List livingInfoDtoList; - try { - ObjectMapper objectMapper = new ObjectMapper(); - - JsonNode jsonNode1 = objectMapper.readTree(responseBody1); -// log.info("feelliketemp = {}", jsonNode1); - - JsonNode temp = jsonNode1.get("main"); - - JsonNode jsonNode2 = objectMapper.readTree(responseBody2); -// log.info("uv = {}", jsonNode2); - - JsonNode uv = jsonNode2.get("response").get("body").get("items").get("item"); - - if (temp != null && uv != null) { - String feelsLike = temp.get("feels_like").asText(); - - JsonNode firstItem = uv.get(0); - String uvi = firstItem.get("h0").asText(); - - LivingInfoDto livingInfoDto = new LivingInfoDto(); - livingInfoDto.setFeels_like(feelsLike); - livingInfoDto.setUvi(uvi); - - livingInfoDtoList = new ArrayList<>(); - livingInfoDtoList.add(livingInfoDto); - } else { - livingInfoDtoList = new ArrayList<>(); - } - -// log.debug("livingInfoDtoList:" + livingInfoDtoList); - return livingInfoDtoList; - } catch (JsonProcessingException e) { - throw new BaseException(ResponseStatus.CANNOT_CONVERT_JSON); - } + return responseBody; + } + + public List ParsingJson(String responseBody1, String responseBody2) + throws BaseException { + List livingInfoDtoList; + try { + ObjectMapper objectMapper = new ObjectMapper(); + + JsonNode jsonNode1 = objectMapper.readTree(responseBody1); + JsonNode temp = jsonNode1.get("main"); + JsonNode jsonNode2 = objectMapper.readTree(responseBody2); + JsonNode uv = jsonNode2.get("response").get("body").get("items").get("item"); + + if (temp != null && uv != null) { + String feelsLike = temp.get("feels_like").asText(); + + JsonNode firstItem = uv.get(0); + String uvi = firstItem.get("h0").asText(); + + LivingInfoDto livingInfoDto = new LivingInfoDto(); + livingInfoDto.setFeels_like(feelsLike); + livingInfoDto.setUvi(uvi); + + livingInfoDtoList = new ArrayList<>(); + livingInfoDtoList.add(livingInfoDto); + } else { + livingInfoDtoList = new ArrayList<>(); + } + + return livingInfoDtoList; + } catch (JsonProcessingException e) { + throw new BaseException(ResponseStatus.CANNOT_CONVERT_JSON); } + } + public boolean isJson(String jsonString) throws BaseException { + boolean isJson = jsonString.startsWith("{") && jsonString.endsWith("}"); - public boolean isJson(String jsonString) throws BaseException { - boolean isJson = jsonString.startsWith("{") && jsonString.endsWith("}"); - - if (!isJson) { - throw new BaseException(ResponseStatus.INVALID_XML_FORMAT); - } else { - return true; - } + if (!isJson) { + throw new BaseException(ResponseStatus.INVALID_XML_FORMAT); + } else { + return true; } + } } diff --git a/src/main/java/com/haemil/backend/weather/service/LocationService.java b/src/main/java/com/haemil/backend/weather/service/LocationService.java index ed20ddc..4e66101 100644 --- a/src/main/java/com/haemil/backend/weather/service/LocationService.java +++ b/src/main/java/com/haemil/backend/weather/service/LocationService.java @@ -3,11 +3,9 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import com.haemil.backend.alert.dto.ReqCoordDto; import com.haemil.backend.global.config.BaseException; import com.haemil.backend.global.config.ResponseStatus; import com.haemil.backend.weather.dto.LivingDto; -import com.haemil.backend.weather.dto.StationDto; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Value; import lombok.extern.slf4j.Slf4j; @@ -16,7 +14,6 @@ import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; -import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.client.RestTemplate; import javax.servlet.http.HttpServletRequest; @@ -28,58 +25,58 @@ @Service @RequiredArgsConstructor public class LocationService { - private final RestTemplate restTemplate; - @Value("${api.hj-kakao-key}") - String serviceKey; + private final RestTemplate restTemplate; - public String getLocationInfo(HttpServletRequest request) throws BaseException { - String responseBody; - try { - String latitude = request.getParameter("latitude"); - String longitude = request.getParameter("longitude"); -// log.info("location - latitude = {}", latitude); -// log.info("location - longitude = {}", longitude); + @Value("${api.hj-kakao-key}") + String serviceKey; - HttpHeaders headers = new HttpHeaders(); - headers.add("Authorization", "KakaoAK " + serviceKey); + public String getLocationInfo(HttpServletRequest request) throws BaseException { + String responseBody; + try { + String latitude = request.getParameter("latitude"); + String longitude = request.getParameter("longitude"); - StringBuilder urlBuilder = new StringBuilder("https://dapi.kakao.com/v2/local/geo/coord2regioncode.json"); - urlBuilder.append("?"+ URLEncoder.encode("x", "UTF-8")+"="+URLEncoder.encode(longitude, "UTF-8")); - urlBuilder.append("&"+ URLEncoder.encode("y", "UTF-8")+"="+URLEncoder.encode(latitude, "UTF-8")); + HttpHeaders headers = new HttpHeaders(); + headers.add("Authorization", "KakaoAK " + serviceKey); - URI url = new URI(urlBuilder.toString()); - RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, url); + StringBuilder urlBuilder = + new StringBuilder("https://dapi.kakao.com/v2/local/geo/coord2regioncode.json"); + urlBuilder.append( + "?" + URLEncoder.encode("x", "UTF-8") + "=" + URLEncoder.encode(longitude, "UTF-8")); + urlBuilder.append( + "&" + URLEncoder.encode("y", "UTF-8") + "=" + URLEncoder.encode(latitude, "UTF-8")); - ResponseEntity response = restTemplate.exchange(requestEntity, String.class); - responseBody = response.getBody(); + URI url = new URI(urlBuilder.toString()); + RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, url); -// log.info("urlBuilder: " + urlBuilder); -// log.info("responseBody: " + responseBody); - } catch (UnsupportedEncodingException e) { - log.debug("UnsupportedEncodingException 발생 "); - throw new BaseException(ResponseStatus.UNSUPPORTED_ENCODING); - } catch (Exception e) { - log.debug("INVALID_XML_FORMAT Exception 발생"); - throw new BaseException(ResponseStatus.INVALID_XML_FORMAT); - } - return responseBody; + ResponseEntity response = restTemplate.exchange(requestEntity, String.class); + responseBody = response.getBody(); + + } catch (UnsupportedEncodingException e) { + log.debug("UnsupportedEncodingException 발생 "); + throw new BaseException(ResponseStatus.UNSUPPORTED_ENCODING); + } catch (Exception e) { + log.debug("INVALID_XML_FORMAT Exception 발생"); + throw new BaseException(ResponseStatus.INVALID_XML_FORMAT); } + return responseBody; + } - public LivingDto getLocation(String responseBody) throws BaseException { - try { - LivingDto livingDto = new LivingDto(); - ObjectMapper objectMapper = new ObjectMapper(); + public LivingDto getLocation(String responseBody) throws BaseException { + try { + LivingDto livingDto = new LivingDto(); + ObjectMapper objectMapper = new ObjectMapper(); - JsonNode jsonNode = objectMapper.readTree(responseBody); - JsonNode documentsNode = jsonNode.get("documents"); - JsonNode itemNode = documentsNode.get(0); + JsonNode jsonNode = objectMapper.readTree(responseBody); + JsonNode documentsNode = jsonNode.get("documents"); + JsonNode itemNode = documentsNode.get(0); - String code = itemNode.get("code").asText(); - livingDto.setAreaNo(code); + String code = itemNode.get("code").asText(); + livingDto.setAreaNo(code); - return livingDto; - } catch (JsonProcessingException e) { - throw new BaseException(ResponseStatus.CANNOT_CONVERT_JSON); - } + return livingDto; + } catch (JsonProcessingException e) { + throw new BaseException(ResponseStatus.CANNOT_CONVERT_JSON); } + } } diff --git a/src/main/java/com/haemil/backend/weather/service/StationService.java b/src/main/java/com/haemil/backend/weather/service/StationService.java index 092cd51..db23683 100644 --- a/src/main/java/com/haemil/backend/weather/service/StationService.java +++ b/src/main/java/com/haemil/backend/weather/service/StationService.java @@ -14,73 +14,70 @@ import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; -import javax.servlet.http.HttpServletRequest; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; - @Slf4j @Service @RequiredArgsConstructor public class StationService { - private final RestTemplate restTemplate; - private final TransferService transferService; - @Value("${api.hj-secret-key}") - String serviceKey; - - private final StationDto stationDto; - - public String getStationInfo(TransferDto transferDto) throws BaseException { - String responseBody; - try { - String apiUrl = stationDto.getApiUrl(); - String returnType = stationDto.getReturnType(); - String tmX = transferService.getTmInfo(transferService.getTransferInfo(transferDto)).getTmX(); // 받아오기 by TransferService - String tmY = transferService.getTmInfo(transferService.getTransferInfo(transferDto)).getTmY(); // 받아오기 by TransferService - - StringBuilder urlBuilder = new StringBuilder(apiUrl); - urlBuilder.append("?"+ URLEncoder.encode("serviceKey", "UTF-8")+"="+serviceKey); - urlBuilder.append("&"+ URLEncoder.encode("returnType", "UTF-8")+"="+URLEncoder.encode(returnType, "UTF-8")); - urlBuilder.append("&"+ URLEncoder.encode("tmX", "UTF-8")+"="+tmX); - urlBuilder.append("&"+ URLEncoder.encode("tmY", "UTF-8")+"="+tmY); - - ResponseEntity response = restTemplate.getForEntity(urlBuilder.toString(), String.class); - - responseBody = response.getBody(); - -// log.info("station_urlBuilder: " + urlBuilder); -// log.info("station_responseBody: " + responseBody); - } catch (UnsupportedEncodingException e) { - log.debug("UnsupportedEncodingException 발생 "); - throw new BaseException(ResponseStatus.UNSUPPORTED_ENCODING); - } - return responseBody; + private final RestTemplate restTemplate; + private final TransferService transferService; + + @Value("${api.hj-secret-key}") + String serviceKey; + + private final StationDto stationDto; + + public String getStationInfo(TransferDto transferDto) throws BaseException { + String responseBody; + try { + String apiUrl = stationDto.getApiUrl(); + String returnType = stationDto.getReturnType(); + String tmX = + transferService + .getTmInfo(transferService.getTransferInfo(transferDto)) + .getTmX(); // 받아오기 by TransferService + String tmY = + transferService + .getTmInfo(transferService.getTransferInfo(transferDto)) + .getTmY(); // 받아오기 by TransferService + + StringBuilder urlBuilder = new StringBuilder(apiUrl); + urlBuilder.append("?" + URLEncoder.encode("serviceKey", "UTF-8") + "=" + serviceKey); + urlBuilder.append( + "&" + + URLEncoder.encode("returnType", "UTF-8") + + "=" + + URLEncoder.encode(returnType, "UTF-8")); + urlBuilder.append("&" + URLEncoder.encode("tmX", "UTF-8") + "=" + tmX); + urlBuilder.append("&" + URLEncoder.encode("tmY", "UTF-8") + "=" + tmY); + + ResponseEntity response = + restTemplate.getForEntity(urlBuilder.toString(), String.class); + + responseBody = response.getBody(); + + } catch (UnsupportedEncodingException e) { + log.debug("UnsupportedEncodingException 발생 "); + throw new BaseException(ResponseStatus.UNSUPPORTED_ENCODING); } + return responseBody; + } - public String getStationName(String responseBody) throws BaseException { - try { - ObjectMapper objectMapper = new ObjectMapper(); - - JsonNode jsonNode = objectMapper.readTree(responseBody); - JsonNode itemsNode = jsonNode.get("response").get("body").get("items"); - JsonNode itemNode = itemsNode.get(0); + public String getStationName(String responseBody) throws BaseException { + try { + ObjectMapper objectMapper = new ObjectMapper(); - String stationName = itemNode.get("stationName").asText(); - -// log.info("stationName:" + stationName); - return stationName; - } catch (JsonProcessingException e) { - throw new BaseException(ResponseStatus.CANNOT_CONVERT_JSON); - } - } + JsonNode jsonNode = objectMapper.readTree(responseBody); + JsonNode itemsNode = jsonNode.get("response").get("body").get("items"); + JsonNode itemNode = itemsNode.get(0); - public boolean isJson(String jsonString) throws BaseException { - boolean isJson = jsonString.startsWith("{") && jsonString.endsWith("}"); + String stationName = itemNode.get("stationName").asText(); - if (!isJson) { - throw new BaseException(ResponseStatus.INVALID_XML_FORMAT); - } else { - return true; - } + return stationName; + } catch (JsonProcessingException e) { + throw new BaseException(ResponseStatus.CANNOT_CONVERT_JSON); } + } } diff --git a/src/main/java/com/haemil/backend/weather/service/TransferService.java b/src/main/java/com/haemil/backend/weather/service/TransferService.java index 4bfec69..168f4bc 100644 --- a/src/main/java/com/haemil/backend/weather/service/TransferService.java +++ b/src/main/java/com/haemil/backend/weather/service/TransferService.java @@ -5,7 +5,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.haemil.backend.global.config.BaseException; import com.haemil.backend.global.config.ResponseStatus; -import com.haemil.backend.weather.controller.AirController; import com.haemil.backend.weather.dto.StationDto; import com.haemil.backend.weather.dto.TransferDto; import lombok.RequiredArgsConstructor; @@ -18,7 +17,6 @@ import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; -import javax.servlet.http.HttpServletRequest; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLEncoder; @@ -27,70 +25,76 @@ @Service @RequiredArgsConstructor public class TransferService { - private final RestTemplate restTemplate; - @Value("${api.hj-kakao-key}") - String serviceKey; - AirController airController; - - public String getTransferInfo(TransferDto transferDto2) throws BaseException { - String responseBody; - - TransferDto transferDto = transferDto2; - - try { - String x = transferDto.getY(); - String y = transferDto.getX(); - String input_coord = "WGS84"; - String output_coord = "TM"; - - HttpHeaders headers = new HttpHeaders(); - headers.add("Authorization", "KakaoAK " + serviceKey); - -// log.debug("serviceKey: " + serviceKey); - - StringBuilder urlBuilder = new StringBuilder("https://dapi.kakao.com/v2/local/geo/transcoord.json"); - urlBuilder.append("?"+ URLEncoder.encode("x", "UTF-8")+"="+URLEncoder.encode(x, "UTF-8")); - urlBuilder.append("&"+ URLEncoder.encode("y", "UTF-8")+"="+URLEncoder.encode(y, "UTF-8")); - urlBuilder.append("&"+ URLEncoder.encode("input_coord", "UTF-8")+"="+URLEncoder.encode(input_coord, "UTF-8")); - urlBuilder.append("&"+ URLEncoder.encode("output_coord", "UTF-8")+"="+URLEncoder.encode(output_coord, "UTF-8")); - - URI url = new URI(urlBuilder.toString()); - RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, url); - - ResponseEntity response = restTemplate.exchange(requestEntity, String.class); - responseBody = response.getBody(); - -// log.info("urlBuilder: " + urlBuilder); -// log.info("responseBody: " + responseBody); - } catch (UnsupportedEncodingException e) { - log.debug("UnsupportedEncodingException 발생 "); - throw new BaseException(ResponseStatus.UNSUPPORTED_ENCODING); - } catch (Exception e) { - log.debug("INVALID_XML_FORMAT Exception 발생"); - throw new BaseException(ResponseStatus.INVALID_XML_FORMAT); - } - return responseBody; + private final RestTemplate restTemplate; + + @Value("${api.hj-kakao-key}") + String serviceKey; + + public String getTransferInfo(TransferDto transferDto2) throws BaseException { + String responseBody; + + TransferDto transferDto = transferDto2; + + try { + String x = transferDto.getY(); + String y = transferDto.getX(); + String input_coord = "WGS84"; + String output_coord = "TM"; + + HttpHeaders headers = new HttpHeaders(); + headers.add("Authorization", "KakaoAK " + serviceKey); + + StringBuilder urlBuilder = + new StringBuilder("https://dapi.kakao.com/v2/local/geo/transcoord.json"); + urlBuilder.append( + "?" + URLEncoder.encode("x", "UTF-8") + "=" + URLEncoder.encode(x, "UTF-8")); + urlBuilder.append( + "&" + URLEncoder.encode("y", "UTF-8") + "=" + URLEncoder.encode(y, "UTF-8")); + urlBuilder.append( + "&" + + URLEncoder.encode("input_coord", "UTF-8") + + "=" + + URLEncoder.encode(input_coord, "UTF-8")); + urlBuilder.append( + "&" + + URLEncoder.encode("output_coord", "UTF-8") + + "=" + + URLEncoder.encode(output_coord, "UTF-8")); + + URI url = new URI(urlBuilder.toString()); + RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, url); + + ResponseEntity response = restTemplate.exchange(requestEntity, String.class); + responseBody = response.getBody(); + + } catch (UnsupportedEncodingException e) { + log.debug("UnsupportedEncodingException 발생 "); + throw new BaseException(ResponseStatus.UNSUPPORTED_ENCODING); + } catch (Exception e) { + log.debug("INVALID_XML_FORMAT Exception 발생"); + throw new BaseException(ResponseStatus.INVALID_XML_FORMAT); } - - // tmX , tmY -> Station 으로 넘기기 - public StationDto getTmInfo(String responseBody) throws BaseException { - try { -// log.debug("transfer - tminfo = {}", responseBody); - StationDto stationDto = new StationDto(); - ObjectMapper objectMapper = new ObjectMapper(); - - JsonNode jsonNode = objectMapper.readTree(responseBody); - JsonNode documentsNode = jsonNode.get("documents"); - JsonNode itemNode = documentsNode.get(0); - - String x = itemNode.get("x").asText(); - String y = itemNode.get("y").asText(); - stationDto.setTmX(x); - stationDto.setTmY(y); - - return stationDto; - } catch (JsonProcessingException e) { - throw new BaseException(ResponseStatus.CANNOT_CONVERT_JSON); - } + return responseBody; + } + + // tmX , tmY -> Station 으로 넘기기 + public StationDto getTmInfo(String responseBody) throws BaseException { + try { + StationDto stationDto = new StationDto(); + ObjectMapper objectMapper = new ObjectMapper(); + + JsonNode jsonNode = objectMapper.readTree(responseBody); + JsonNode documentsNode = jsonNode.get("documents"); + JsonNode itemNode = documentsNode.get(0); + + String x = itemNode.get("x").asText(); + String y = itemNode.get("y").asText(); + stationDto.setTmX(x); + stationDto.setTmY(y); + + return stationDto; + } catch (JsonProcessingException e) { + throw new BaseException(ResponseStatus.CANNOT_CONVERT_JSON); } + } } diff --git a/src/main/java/com/haemil/backend/weather/service/WeatherService.java b/src/main/java/com/haemil/backend/weather/service/WeatherService.java index 327894c..68aa208 100644 --- a/src/main/java/com/haemil/backend/weather/service/WeatherService.java +++ b/src/main/java/com/haemil/backend/weather/service/WeatherService.java @@ -25,219 +25,247 @@ @Service @RequiredArgsConstructor public class WeatherService { - private final RestTemplate restTemplate; - - @Value("${api.hj-secret-key}") - private String serviceKey; - - public String getWeatherInfo(WeatherDto weatherDto) throws BaseException { - String responseBody; - try { - String apiUrl = weatherDto.getApiUrl(); - String type = weatherDto.getDataType(); - String numOfRows = weatherDto.getNumOfRows(); - String pageNo = weatherDto.getPageNo(); - String base_date = weatherDto.getBase_date(); - String base_time = weatherDto.getBase_time(); - String nx = weatherDto.getNx(); - String ny = weatherDto.getNy(); - - StringBuilder urlBuilder = new StringBuilder(apiUrl); - urlBuilder.append("?" + URLEncoder.encode("serviceKey", "UTF-8") + "=" + serviceKey); - urlBuilder.append("&" + URLEncoder.encode("dataType", "UTF-8") + "=" + URLEncoder.encode(type, "UTF-8")); - urlBuilder.append("&" + URLEncoder.encode("numOfRows", "UTF-8") + "=" + URLEncoder.encode(numOfRows, "UTF-8")); - urlBuilder.append("&" + URLEncoder.encode("pageNo", "UTF-8") + "=" + URLEncoder.encode(pageNo, "UTF-8")); - urlBuilder.append("&" + URLEncoder.encode("base_date", "UTF-8") + "=" + URLEncoder.encode(base_date, "UTF-8")); - urlBuilder.append("&" + URLEncoder.encode("base_time", "UTF-8") + "=" + URLEncoder.encode(base_time, "UTF-8")); - urlBuilder.append("&" + URLEncoder.encode("nx", "UTF-8") + "=" + URLEncoder.encode(nx, "UTF-8")); - urlBuilder.append("&" + URLEncoder.encode("ny", "UTF-8") + "=" + URLEncoder.encode(ny, "UTF-8")); - - ResponseEntity response = restTemplate.getForEntity(urlBuilder.toString(), String.class); - - responseBody = response.getBody(); - } catch (UnsupportedEncodingException e) { - throw new BaseException(ResponseStatus.UNSUPPORTED_ENCODING); - } - return responseBody; + private final RestTemplate restTemplate; + + @Value("${api.hj-secret-key}") + private String serviceKey; + + public String getWeatherInfo(WeatherDto weatherDto) throws BaseException { + String responseBody; + try { + String apiUrl = weatherDto.getApiUrl(); + String type = weatherDto.getDataType(); + String numOfRows = weatherDto.getNumOfRows(); + String pageNo = weatherDto.getPageNo(); + String base_date = weatherDto.getBase_date(); + String base_time = weatherDto.getBase_time(); + String nx = weatherDto.getNx(); + String ny = weatherDto.getNy(); + + StringBuilder urlBuilder = new StringBuilder(apiUrl); + urlBuilder.append("?" + URLEncoder.encode("serviceKey", "UTF-8") + "=" + serviceKey); + urlBuilder.append( + "&" + URLEncoder.encode("dataType", "UTF-8") + "=" + URLEncoder.encode(type, "UTF-8")); + urlBuilder.append( + "&" + + URLEncoder.encode("numOfRows", "UTF-8") + + "=" + + URLEncoder.encode(numOfRows, "UTF-8")); + urlBuilder.append( + "&" + URLEncoder.encode("pageNo", "UTF-8") + "=" + URLEncoder.encode(pageNo, "UTF-8")); + urlBuilder.append( + "&" + + URLEncoder.encode("base_date", "UTF-8") + + "=" + + URLEncoder.encode(base_date, "UTF-8")); + urlBuilder.append( + "&" + + URLEncoder.encode("base_time", "UTF-8") + + "=" + + URLEncoder.encode(base_time, "UTF-8")); + urlBuilder.append( + "&" + URLEncoder.encode("nx", "UTF-8") + "=" + URLEncoder.encode(nx, "UTF-8")); + urlBuilder.append( + "&" + URLEncoder.encode("ny", "UTF-8") + "=" + URLEncoder.encode(ny, "UTF-8")); + + ResponseEntity response = + restTemplate.getForEntity(urlBuilder.toString(), String.class); + + responseBody = response.getBody(); + } catch (UnsupportedEncodingException e) { + throw new BaseException(ResponseStatus.UNSUPPORTED_ENCODING); } - - public List ParsingJson(String responseBody) throws BaseException { - List weatherInfoDtoList; - try { - List weatherApiList = new ArrayList<>(); - ObjectMapper objectMapper = new ObjectMapper(); - - JsonNode jsonNode = objectMapper.readTree(responseBody); - JsonNode itemsNode = jsonNode.get("response").get("body").get("items"); - JsonNode itemNode = itemsNode.get("item"); - - if (itemNode.isArray()) { - for (JsonNode node : itemNode) { - String fcstDate = node.get("fcstDate").asText(); - String fcstTime = node.get("fcstTime").asText(); - String category = node.get("category").asText(); - String fcstValue = node.get("fcstValue").asText(); - - WeatherInfoDto weatherInfoDto = new WeatherInfoDto(); - weatherInfoDto.setFcstDate(fcstDate); - weatherInfoDto.setFcstTime(fcstTime); - weatherInfoDto.setCategory(category); - weatherInfoDto.setFcstValue(fcstValue); - weatherApiList.add(weatherInfoDto); - } - } - - weatherInfoDtoList = new ArrayList<>(weatherApiList); - } catch (JsonProcessingException e) { - throw new BaseException(ResponseStatus.CANNOT_CONVERT_JSON); + return responseBody; + } + + public List ParsingJson(String responseBody) throws BaseException { + List weatherInfoDtoList; + try { + List weatherApiList = new ArrayList<>(); + ObjectMapper objectMapper = new ObjectMapper(); + + JsonNode jsonNode = objectMapper.readTree(responseBody); + JsonNode itemsNode = jsonNode.get("response").get("body").get("items"); + JsonNode itemNode = itemsNode.get("item"); + + if (itemNode.isArray()) { + for (JsonNode node : itemNode) { + String fcstDate = node.get("fcstDate").asText(); + String fcstTime = node.get("fcstTime").asText(); + String category = node.get("category").asText(); + String fcstValue = node.get("fcstValue").asText(); + + WeatherInfoDto weatherInfoDto = new WeatherInfoDto(); + weatherInfoDto.setFcstDate(fcstDate); + weatherInfoDto.setFcstTime(fcstTime); + weatherInfoDto.setCategory(category); + weatherInfoDto.setFcstValue(fcstValue); + weatherApiList.add(weatherInfoDto); } - return weatherInfoDtoList; - } - - public boolean isJson(String xmlString) throws BaseException { - boolean isJson = xmlString.startsWith("{") && xmlString.endsWith("}"); + } - if (!isJson) { - throw new BaseException(ResponseStatus.INVALID_XML_FORMAT); - } else { - return true; - } + weatherInfoDtoList = new ArrayList<>(weatherApiList); + } catch (JsonProcessingException e) { + throw new BaseException(ResponseStatus.CANNOT_CONVERT_JSON); } + return weatherInfoDtoList; + } - public List filterCurrentTimeData(List weatherInfoDtoList, WeatherDto weatherDto) { - List filteredList = new ArrayList<>(); - - for (WeatherInfoDto weatherInfoDto : weatherInfoDtoList) { - String fcstDate = weatherInfoDto.getFcstDate(); - String fcstTime = weatherInfoDto.getFcstTime(); + public boolean isJson(String xmlString) throws BaseException { + boolean isJson = xmlString.startsWith("{") && xmlString.endsWith("}"); - if (fcstDate.equals(weatherDto.getBase_date()) && fcstTime.equals(weatherDto.getCurrent_time())) { - filteredList.add(weatherInfoDto); - } - } - - return filteredList; + if (!isJson) { + throw new BaseException(ResponseStatus.INVALID_XML_FORMAT); + } else { + return true; } + } - public Map transformWeatherData(List weatherInfoDtoList, List todayData, WeatherDto weatherDto) { - List Result = new ArrayList<>(); - Map resultData = new HashMap<>(); + public List filterCurrentTimeData( + List weatherInfoDtoList, WeatherDto weatherDto) { + List filteredList = new ArrayList<>(); - for (WeatherInfoDto today : todayData) { - String fcstValue = today.getFcstValue(); - String category = today.getCategory(); + for (WeatherInfoDto weatherInfoDto : weatherInfoDtoList) { + String fcstDate = weatherInfoDto.getFcstDate(); + String fcstTime = weatherInfoDto.getFcstTime(); - if (category.equals("TMP")) { - resultData.put("current", fcstValue); - break; - } - } + if (fcstDate.equals(weatherDto.getBase_date()) + && fcstTime.equals(weatherDto.getCurrent_time())) { + filteredList.add(weatherInfoDto); + } + } - for (WeatherInfoDto weatherInfoDto : weatherInfoDtoList) { - String fcstDate = weatherInfoDto.getFcstDate(); - String fcstValue = weatherInfoDto.getFcstValue(); + return filteredList; + } - if (fcstDate.equals(weatherDto.getBase_date())) { - String category = weatherInfoDto.getCategory(); + public Map transformWeatherData( + List weatherInfoDtoList, + List todayData, + WeatherDto weatherDto) { + Map resultData = new HashMap<>(); - if (category.equals("TMN")) { - resultData.put("min", fcstValue); - } else if (category.equals("TMX")) { - resultData.put("max", fcstValue); - } - } - } + for (WeatherInfoDto today : todayData) { + String fcstValue = today.getFcstValue(); + String category = today.getCategory(); - return resultData; + if (category.equals("TMP")) { + resultData.put("current", fcstValue); + break; + } } - public List> filterCurrentTimeAndSpecifiedDateData(List weatherInfoDtoList, String specifiedTime) { - Map> groupedData = new HashMap<>(); - - for (WeatherInfoDto weatherInfoDto : weatherInfoDtoList) { - String fcstDate = weatherInfoDto.getFcstDate(); - String fcstTime = weatherInfoDto.getFcstTime(); - String fcstValue = weatherInfoDto.getFcstValue(); - String category = weatherInfoDto.getCategory(); - - // "fcstTime"이 "1500"이고 오늘, 내일 또는 모레인 데이터만 필터링 - if (fcstTime.equals(specifiedTime) && isSpecifiedDate(fcstDate) && (category.equals("TMP") || category.equals("SKY"))) { - // 날짜별로 데이터 그룹화 - String key = fcstDate + fcstTime; - groupedData.putIfAbsent(key, new HashMap<>()); - Map dataPoint = groupedData.get(key); - - dataPoint.put("fcstDate", fcstDate); - dataPoint.put("fcstTime", fcstTime); - - if (category.equals("TMP")) { - dataPoint.put("TMP", fcstValue); - } - - if (category.equals("SKY")) { - dataPoint.put("SKY", fcstValue); - } - } - } + for (WeatherInfoDto weatherInfoDto : weatherInfoDtoList) { + String fcstDate = weatherInfoDto.getFcstDate(); + String fcstValue = weatherInfoDto.getFcstValue(); - List> resultList = new ArrayList<>(groupedData.values()); - resultList.sort(Comparator.comparing(dataPoint -> dataPoint.get("fcstDate"))); + if (fcstDate.equals(weatherDto.getBase_date())) { + String category = weatherInfoDto.getCategory(); - return resultList; + if (category.equals("TMN")) { + resultData.put("min", fcstValue); + } else if (category.equals("TMX")) { + resultData.put("max", fcstValue); + } + } } - private boolean isSpecifiedDate(String fcstDate) { - LocalDate today = LocalDate.now(); - LocalDate tomorrow = today.plusDays(1); - LocalDate dayAfterTomorrow = today.plusDays(2); - - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd"); - LocalDate parsedFcstDate = LocalDate.parse(fcstDate, formatter); + return resultData; + } + + public List> filterCurrentTimeAndSpecifiedDateData( + List weatherInfoDtoList, String specifiedTime) { + Map> groupedData = new HashMap<>(); + + for (WeatherInfoDto weatherInfoDto : weatherInfoDtoList) { + String fcstDate = weatherInfoDto.getFcstDate(); + String fcstTime = weatherInfoDto.getFcstTime(); + String fcstValue = weatherInfoDto.getFcstValue(); + String category = weatherInfoDto.getCategory(); + + // "fcstTime"이 "1500"이고 오늘, 내일 또는 모레인 데이터만 필터링 + if (fcstTime.equals(specifiedTime) + && isSpecifiedDate(fcstDate) + && (category.equals("TMP") || category.equals("SKY"))) { + // 날짜별로 데이터 그룹화 + String key = fcstDate + fcstTime; + groupedData.putIfAbsent(key, new HashMap<>()); + Map dataPoint = groupedData.get(key); + + dataPoint.put("fcstDate", fcstDate); + dataPoint.put("fcstTime", fcstTime); + + if (category.equals("TMP")) { + dataPoint.put("TMP", fcstValue); + } - return parsedFcstDate.equals(today) || parsedFcstDate.equals(tomorrow) || parsedFcstDate.equals(dayAfterTomorrow); + if (category.equals("SKY")) { + dataPoint.put("SKY", fcstValue); + } + } } - - public List> filterNextData(List weatherInfoDtoList, LocalTime startTime, int numDataPoints) { - List> filteredList = new ArrayList<>(); - - DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH00"); - - for (int i = 0; i < numDataPoints; i++) { - LocalTime nextTime = startTime.plusHours(i); - String formattedNextTime = nextTime.format(timeFormatter); - - Map dataPoint = new HashMap<>(); - boolean hasTmp = false; - boolean hasSky = false; - - String fcstDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")); // 현재 날짜를 사용 - String fcstTime = formattedNextTime; - - for (WeatherInfoDto weatherInfoDto : weatherInfoDtoList) { - String category = weatherInfoDto.getCategory(); - String fcstValue = weatherInfoDto.getFcstValue(); - - if (weatherInfoDto.getFcstDate().equals(fcstDate) && weatherInfoDto.getFcstTime().equals(fcstTime) && (category.equals("TMP") || category.equals("SKY"))) { - if (category.equals("TMP")) { - dataPoint.put("TMP", fcstValue); - hasTmp = true; - } else if (category.equals("SKY")) { - dataPoint.put("SKY", fcstValue); - hasSky = true; - } - - if (hasTmp && hasSky) { - dataPoint.put("FCST_DATE", fcstDate); - dataPoint.put("FCST_TIME", fcstTime); - filteredList.add(dataPoint); - break; - } - } - } + List> resultList = new ArrayList<>(groupedData.values()); + resultList.sort(Comparator.comparing(dataPoint -> dataPoint.get("fcstDate"))); + + return resultList; + } + + private boolean isSpecifiedDate(String fcstDate) { + LocalDate today = LocalDate.now(); + LocalDate tomorrow = today.plusDays(1); + LocalDate dayAfterTomorrow = today.plusDays(2); + + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd"); + LocalDate parsedFcstDate = LocalDate.parse(fcstDate, formatter); + + return parsedFcstDate.equals(today) + || parsedFcstDate.equals(tomorrow) + || parsedFcstDate.equals(dayAfterTomorrow); + } + + public List> filterNextData( + List weatherInfoDtoList, LocalTime startTime, int numDataPoints) { + List> filteredList = new ArrayList<>(); + + DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH00"); + + for (int i = 0; i < numDataPoints; i++) { + LocalTime nextTime = startTime.plusHours(i); + String formattedNextTime = nextTime.format(timeFormatter); + + Map dataPoint = new HashMap<>(); + boolean hasTmp = false; + boolean hasSky = false; + + String fcstDate = + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")); // 현재 날짜를 사용 + String fcstTime = formattedNextTime; + + for (WeatherInfoDto weatherInfoDto : weatherInfoDtoList) { + String category = weatherInfoDto.getCategory(); + String fcstValue = weatherInfoDto.getFcstValue(); + + if (weatherInfoDto.getFcstDate().equals(fcstDate) + && weatherInfoDto.getFcstTime().equals(fcstTime) + && (category.equals("TMP") || category.equals("SKY"))) { + if (category.equals("TMP")) { + dataPoint.put("TMP", fcstValue); + hasTmp = true; + } else if (category.equals("SKY")) { + dataPoint.put("SKY", fcstValue); + hasSky = true; + } + + if (hasTmp && hasSky) { + dataPoint.put("FCST_DATE", fcstDate); + dataPoint.put("FCST_TIME", fcstTime); + filteredList.add(dataPoint); + break; + } } - - return filteredList; + } } + return filteredList; + } }