diff --git a/pav-server/src/main/java/com/palnet/biz/scheduler/external/SunRiseSetScheduler.java b/pav-server/src/main/java/com/palnet/biz/scheduler/external/SunRiseSetScheduler.java new file mode 100644 index 00000000..65b4799d --- /dev/null +++ b/pav-server/src/main/java/com/palnet/biz/scheduler/external/SunRiseSetScheduler.java @@ -0,0 +1,19 @@ +package com.palnet.biz.scheduler.external; + +import com.palnet.biz.scheduler.external.service.SunRiseSchedulerService; +import lombok.RequiredArgsConstructor; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +@Component +@RequiredArgsConstructor +public class SunRiseSetScheduler { + + private final SunRiseSchedulerService sunRiseSchedulerService; + +// @Scheduled(cron = "* 0/30 * * * *") + public void run(){ + sunRiseSchedulerService.sunsetSchedule(); + } + +} diff --git a/pav-server/src/main/java/com/palnet/biz/scheduler/external/service/SunRiseSchedulerService.java b/pav-server/src/main/java/com/palnet/biz/scheduler/external/service/SunRiseSchedulerService.java new file mode 100644 index 00000000..3e2f1143 --- /dev/null +++ b/pav-server/src/main/java/com/palnet/biz/scheduler/external/service/SunRiseSchedulerService.java @@ -0,0 +1,219 @@ +package com.palnet.biz.scheduler.external.service; + +import com.palnet.biz.api.external.model.SunRiseSetRs; +import com.palnet.biz.api.external.model.SunRiseSetXmlRs; +import com.palnet.biz.api.external.service.SunRiseSetMapper; +import com.palnet.biz.jpa.entity.ComRiseSetBas; +import com.palnet.biz.jpa.entity.ComRiseSetBasPK; +import com.palnet.biz.jpa.repository.com.ComRiseSetBasRepository; +import com.palnet.comn.code.ErrorCode; +import com.palnet.comn.exception.CustomException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.web.reactive.function.client.WebClient; +import org.springframework.web.util.UriComponentsBuilder; + +import java.lang.reflect.Field; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; + + +@Service +@Slf4j +@RequiredArgsConstructor +public class SunRiseSchedulerService { + + private final ComRiseSetBasRepository comRiseSetBasRepository; + + @Value("${external.sunriseset.url}") + private String SUN_HOST; + + @Value("${external.sunriseset.key}") + private String SUN_KEY; + + private final String AREA_RISE_SEET_INFO_URL = "/getAreaRiseSetInfo"; + + + + private static final String[][][] location = { + { + {"백령도", "연평도", "덕적도", "강화", "격렬비도", "격렬비도", "김포", "인천", "부천", "고양", "시흥", "태안", "광명"}, + {"연세KVN", "안산", "서산", "서울", "의정부", "화성", "양주", "군포", "동두천", "안양", "연천", "과천", "당진"}, + {"의왕", "구리", "포천", "수원", "성남", "남양주", "하남", "오산", "파주", "철원", "경기광주", "용인", "평택"}, + {"가평", "양평", "이천", "화천", "춘천", "홍천", "양구", "인제", "홍천군서석면", "인제군기린면", "강원고성", "속초", "양양"} + }, + { + {"어청도", "보령", "서천", "위도", "군산", "홍성", "청양", "부여", "익산", "예산", "논산", "공주", "계룡"}, + {"아산", "세종", "천안", "대덕전파천문대", "대전", "옥천", "청주", "청주공항", "안성", "진천", "증평", "보은", "음성"}, + {"괴산", "괴산군연풍면", "여주", "충주", "문경", "원주", "제천", "예천", "단양", "횡성", "소백산천문대", "영주", "영월"}, + {"평창", "봉화", "정선", "홍천군내면", "춘양", "태백", "대관령", "평창KVN", "강릉", "주문진", "동해", "삼척"} + }, + { + {"가거도", "흑산도", "신안", "목포", "신안군임자면", "무안", "영암", "함평", "나주", "영광", "광주", "화순", "장성"}, + {"고창", "변산", "담양", "정읍", "순창", "부안", "곡성", "김제", "남원", "임실", "전주", "완주", "장수"}, + {"진안", "함양", "거창", "금산", "무주", "김천시부항면", "영동", "고령", "성주", "추풍령", "김천", "달성", "칠곡"}, + {"구미", "대구", "상주", "군위", "의성", "보현산천문대", "안동", "청송", "영양", "영덕", "울진", "울릉"} + }, + { + {"마라도", "제주레이더", "탐라KVN", "서귀포", "제주", "성산일출", "추자도", "완도", "삼산도", "진도", "해남", "강진", "장흥"}, + {"고흥", "보성", "여수", "여수공항", "순천", "승주", "광양", "남해", "하동", "구례", "사천", "통영", "고성"}, + {"진주", "거제", "산청", "의령", "함안", "합천", "창원", "김해", "창녕", "부산", "밀양", "양산", "진해"}, + {"기장", "청도", "경산", "울주", "울산KVN", "울산", "경주시산내면", "영천", "경주", "경주시감포읍", "포항", "독도"} + } + }; + + private int dateCount = 1; + + public void sunsetSchedule(){ + + List todayLocation = this.todayLocation(); + LocalDate today = LocalDate.now(); + List timeColumn = List.of("sunrise", "suntransit", "sunset", "moonrise", "moontransit", "moonset", "civilm", "civile", "nautm", "naute", "astm", "aste"); + + List sunRiseSet = new ArrayList<>(); + + // 내일부터 약180일 데이터 INSERT + for(int i = 0; i <= 180; i ++){ + today = today.plusDays(1); + String locdate = today.format(DateTimeFormatter.ofPattern("yyyyMMdd")); + + for(int j = 0; j < todayLocation.size(); j ++){ + String location = todayLocation.get(j); + + List results = callSunRiseSet(locdate, location); + // trim 제거 및 6자리로 맞추기 + results.forEach(result -> { + Class aClass = result.getClass(); + Field[] declaredFields = aClass.getDeclaredFields(); + for (Field field: declaredFields){ + if(timeColumn.contains(field.getName())){ + field.setAccessible(true); + try { + Object o = field.get(result); + if(o instanceof String){ + String str = (String) o; + if(!str.isEmpty()) { + String trim = str.trim(); + if(trim.length() <= 6 && trim.length() >= 4 && trim.matches("-?\\d+(\\.\\d+)?")) { + field.set(result, String.format("%-6s", trim).replace(' ', '0')); + } else { + field.set(result, null); + } + } + } + + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + } + } + + ComRiseSetBasPK pk = SunRiseSetMapper.MAPPER.toEntityPk(result); + ComRiseSetBas entity = SunRiseSetMapper.MAPPER.toEntity(result); + entity.setId(pk); + + sunRiseSet.add(entity); + }); + } + + if(i%30 == 0){ + comRiseSetBasRepository.saveAll(sunRiseSet); + + sunRiseSet.clear(); + } + } + } + + private List callSunRiseSet(String locdate, String location) { + + String uriStr = UriComponentsBuilder.fromUriString(AREA_RISE_SEET_INFO_URL) + .queryParam("serviceKey", SUN_KEY) + .queryParam("locdate", locdate) + .queryParam("location", location) + .build().toUriString(); + + WebClient client = WebClient.builder() + .baseUrl(SUN_HOST) + .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) + .build(); + + ResponseEntity resp = client.get() + .uri(uriStr) + .retrieve() + .toEntity(SunRiseSetXmlRs.class) + .block(); + + log.debug(">>> resp : {}", resp); + + List items = resp.getBody().getBody().getItems(); + + return items; + } + + private List todayLocation (){ + int count = this.init(); + int changeCount = this.arraySelect(count); + + List todayLocation = new ArrayList<>(); + + for(int i = 0; i < 4; i ++){ + if(changeCount == 4) changeCount = 0; + String[] arr = this.location[i][changeCount]; + + todayLocation.addAll(Arrays.asList(arr)); + changeCount ++; + } + + // 중복제거 + HashSet set = new HashSet<>(todayLocation); + + return new ArrayList<>(set); + } + + private int arraySelect(int count){ + int result; + + switch (count){ + case 1 : + result = 0; + break; + case 2 : + result = 1; + break; + case 3 : + result= 2; + break; + case 4 : + result = 3; + break; + default: + throw new CustomException(ErrorCode.NON_VALID_PARAMETER); + } + + return result; + } + + + private int init(){ + int result = dateCount; + + if(dateCount == 4){ + dateCount = 0; + } + + dateCount ++; + + return result; + } + + +}