eunja511005 / AutoCoding

0 stars 0 forks source link

:new: [확장] 기상청 단기 예보 메뉴 추가 #103

Open eunja511005 opened 12 months ago

eunja511005 commented 12 months ago
  1. 공공 데이터 검색 : https://www.data.go.kr/

  2. 활용 신청

  3. Talend API Tester 활용하여 테스트

    • 마이페이지 > API신청 > 테스트할 API 선택 > 미리보기 확인 클릭 > 미리보기 클릭 > API 호출 주소로 이동
    • API 주소를 복사하 Talend API Tester에서 테스트 image

      image


      image


      image


      image


      image

  4. API 테이블에 등록

eunja511005 commented 12 months ago

image

eunja511005 commented 12 months ago

이관 필요 테이블

SELECT * FROM COMMON_CODE cc ORDER BY CREATED_AT DESC;
SELECT * FROM ZTHH_SYSTEMMASTER zs ORDER BY CREATE_DT desc;
SELECT * FROM ZTHH_APIMASTER za ORDER BY CREATE_DT desc;
SELECT * FROM ZTHH_MENU zm  ORDER BY CREATE_DT desc;
SELECT * FROM ZTHH_MENUCONTROL zm  ORDER BY CREATE_DT desc;
eunja511005 commented 12 months ago

Talend API Tester에서 jsonString response 데이터 얻기 (pretty 말고 raw로 선택하면 텍스트 데이터 얻을 수 있음)

image

eunja511005 commented 12 months ago

JsonStringToDTOSourceUtils.java 파일에서 json 응답값 이용해서 DTO 만들기

  1. rootClassName 바꾸기
  2. Talend API Tester에서 얻은 json 응답값을 jsonString 변수에 넣기

image

eunja511005 commented 12 months ago

DTO 생성 결과

import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class GetUltraSrtNcstRootDTO {
    @JsonProperty("response")
    private ResponseDTO response;

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class ResponseDTO {
        @JsonProperty("header")
        private HeaderDTO header;
        @JsonProperty("body")
        private BodyDTO body;
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class HeaderDTO {
        @JsonProperty("resultCode")
        private String resultCode;
        @JsonProperty("resultMsg")
        private String resultMsg;
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class BodyDTO {
        @JsonProperty("dataType")
        private String dataType;
        @JsonProperty("items")
        private ItemsDTO items;
        @JsonProperty("pageNo")
        private int pageNo;
        @JsonProperty("numOfRows")
        private int numOfRows;
        @JsonProperty("totalCount")
        private int totalCount;
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class ItemsDTO {
        @JsonProperty("item")
        private List<ItemDTO> item;
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class ItemDTO {
        @JsonProperty("baseDate")
        private String baseDate;
        @JsonProperty("baseTime")
        private String baseTime;
        @JsonProperty("category")
        private String category;
        @JsonProperty("nx")
        private int nx;
        @JsonProperty("ny")
        private int ny;
        @JsonProperty("obsrValue")
        private String obsrValue;
    }

}
eunja511005 commented 12 months ago

DTO 클래스 생성

image

eunja511005 commented 12 months ago

RestTemplateCallUtilTest 테스트 케이스 추가

image


image


image

package com.eun.tutorial.util;

import static org.junit.Assert.assertEquals;

import java.net.URISyntaxException;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestClientException;

import com.eun.tutorial.dto.external.pubdata.GetUltraSrtNcstRootDTO;
import com.eun.tutorial.dto.external.pubdata.RequestDetails;
import com.eun.tutorial.dto.main.ApiMasterDTO;
import com.eun.tutorial.service.main.ApiMasterService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.extern.slf4j.Slf4j;

@SpringBootTest
@Slf4j
class RestTemplateCallUtilTest {

    @Autowired
    RestTemplateCallUtil restTemplateCallUtil;

    @Autowired
    ApiMasterService apiMasterService;

    @Test
    void GetUltraSrtNcstRootDTO() throws RestClientException, URISyntaxException, JsonMappingException, JsonProcessingException {

        // 1. Given
        String apiName = "getUltraSrtNcst";
        String systemName = "PublicPortal";
        ApiMasterDTO apiMasterDTO = apiMasterService.getApiMasterByAPIAndSystemName(apiName, systemName);

        StringBuilder sb = new StringBuilder();
        sb.append(apiMasterDTO.getCallUrl());
        sb.append("?serviceKey="+apiMasterDTO.getAuthor());
        sb.append("&pageNo=1");
        sb.append("&numOfRows=1000");
        sb.append("&dataType=json");
        sb.append("&base_date=20230708");
        sb.append("&base_time=2400");
        sb.append("&nx=55");
        sb.append("&ny=127");

        HttpHeaders headers = new HttpHeaders();
        RequestDetails<Object, String> requestDetails = new RequestDetails<>();
        requestDetails.setEndpointUrl(sb.toString());
        requestDetails.setHttpMethod(apiMasterDTO.getHttpMethod());
        requestDetails.setRequestBody(null);
        requestDetails.setHeaders(headers);
        requestDetails.setRequestMediaType(MediaType.APPLICATION_JSON);
        requestDetails.setResponseMediaType(MediaType.APPLICATION_JSON);
        requestDetails.setResponseType(String.class);
        requestDetails.setLogYn(apiMasterDTO.getLogYn());

        // 2. When
        ResponseEntity<String> response = restTemplateCallUtil.sendRequest(requestDetails);

        String jsonString = response.getBody();

        log.info(" ### response {}", sb.toString());

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);       
        // JSON 문자열을 Map으로 변환
        GetUltraSrtNcstRootDTO getUltraSrtNcstRootDTO = objectMapper.readValue(jsonString, new TypeReference<GetUltraSrtNcstRootDTO>() {});

        // 3. Then
        assertEquals(getUltraSrtNcstRootDTO.getResponse().getHeader().getResultCode(), "00");
    }
}
eunja511005 commented 12 months ago

image


image


image

eunja511005 commented 12 months ago

image

eunja511005 commented 12 months ago

공통 코드 등록(API 명서서의 nx, ny 값 참조) image

eunja511005 commented 12 months ago

image

eunja511005 commented 12 months ago

Service, ServiceImpl, Controller 생성

eunja511005 commented 12 months ago
@Controller
@RequestMapping("/tourismStaying")
@AllArgsConstructor
public class GetUltraSrtNcstController {

    private final GetUltraSrtNcstService tourPriceService;

    @GetMapping("/list")
    public ModelAndView list() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("jsp/external/pubdata/getUltraSrtNcst");
        return modelAndView;
    }

    @PostMapping("/list")
    public @ResponseBody DataTableResult<ItemDTO> searchRealEstatePrice(@RequestBody DataTableRequestDTO searchDTO) throws JsonProcessingException, URISyntaxException {
        return tourPriceService.searchGetUltraSrtNcst(searchDTO);
    }

}
eunja511005 commented 12 months ago
public interface GetUltraSrtNcstService {
    DataTableResult<ItemDTO> searchGetUltraSrtNcst(DataTableRequestDTO searchDTO) throws JsonProcessingException, URISyntaxException;
}
eunja511005 commented 12 months ago
@Service
@Slf4j
@RequiredArgsConstructor
public class GetUltraSrtNcstServiceImpl implements GetUltraSrtNcstService{

    private final RestTemplateCallUtil restTemplateCallUtil;
    private final ApiMasterService apiMasterService;

    @Override
    public DataTableResult<ItemDTO> searchGetUltraSrtNcst(DataTableRequestDTO searchDTO) throws JsonProcessingException, URISyntaxException {
        String apiName = "getUltraSrtNcst";
        String systemName = "PublicPortal";

        ApiMasterDTO apiMasterDTO = apiMasterService.getApiMasterByAPIAndSystemName(apiName, systemName);

        List<ItemDTO> rowDTOList = getApiResult(apiMasterDTO, searchDTO);
        int totalSize = rowDTOList.size();

        return DataTableUtil.getResult(searchDTO, rowDTOList, totalSize);
    }

    private List<ItemDTO> getApiResult(ApiMasterDTO apiMasterDTO, DataTableRequestDTO searchDTO) throws RestClientException, URISyntaxException, JsonProcessingException{

        String sixAgo = DateUtils.getSomeHourAgo(1);
        String date = sixAgo.substring(0, 8);
        String hour = sixAgo.substring(8, 10)+"00";

        StringBuilder sb = new StringBuilder();
        sb.append(apiMasterDTO.getCallUrl());
        sb.append("?serviceKey="+apiMasterDTO.getAuthor());
        sb.append("&dataType=json");
        sb.append("&pageNo="+(searchDTO.getStart()+1));
        sb.append("&numOfRows="+searchDTO.getLength());
        sb.append("&base_date="+date);
        sb.append("&base_time="+hour);
        sb.append("&nx="+searchDTO.getSearch().get("nx").getValue());
        sb.append("&ny="+searchDTO.getSearch().get("ny").getValue());

        // RequestDetails 객체 생성
        HttpHeaders headers = new HttpHeaders();
        RequestDetails<Object, String> requestDetails = new RequestDetails<>();
        requestDetails.setEndpointUrl(sb.toString());
        requestDetails.setHttpMethod(apiMasterDTO.getHttpMethod());
        requestDetails.setRequestBody(null);
        requestDetails.setHeaders(headers);
        requestDetails.setRequestMediaType(MediaType.APPLICATION_JSON);
        requestDetails.setResponseMediaType(MediaType.APPLICATION_JSON);
        requestDetails.setResponseType(String.class);
        requestDetails.setLogYn(apiMasterDTO.getLogYn());

        ResponseEntity<String> response = restTemplateCallUtil.sendRequest(requestDetails);

        String jsonString = response.getBody();

        log.info(" ### response {}", sb.toString());

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        // JSON 문자열을 Map으로 변환
        GetUltraSrtNcstRootDTO getUltraSrtNcstRootDTO = objectMapper.readValue(jsonString, new TypeReference<GetUltraSrtNcstRootDTO>() {});

        return getUltraSrtNcstRootDTO.getResponse().getBody().getItems().getItem();
    }

}
eunja511005 commented 12 months ago

메뉴 등록

Interface 2 ROLE_ANY getUltraSrtNcst /getUltraSrtNcst/list N/A 5 layout

image

eunja511005 commented 12 months ago

getUltraSrtNcst.js, getUltraSrtNcst.jsp 생성

eunja511005 commented 12 months ago

image

eunja511005 commented 12 months ago

image

eunja511005 commented 12 months ago

image

eunja511005 commented 12 months ago

image

eunja511005 commented 12 months ago

image

eunja511005 commented 12 months ago

image

eunja511005 commented 12 months ago

다국어 처리를 위해 message.properties 파일 입력

eunja511005 commented 12 months ago
#####################################################
getUltraSrtNcst=실시간 날씨 정보
field.label.category=날씨 정보 카테고리
field.label.obsrValue=측정 결과
#####################################################
getUltraSrtNcst=getUltraSrtNcst=real-time weather information
field.label.category=field.label.category=weather information category
field.label.obsrValue=measurement result
eunja511005 commented 12 months ago

image

eunja511005 commented 12 months ago

image


image

eunja511005 commented 12 months ago

image

eunja511005 commented 12 months ago

관리자 권한으로(카카오톡) 로그인 후 메뉴 조회해야 Any로 권한 들어 감

image

eunja511005 commented 12 months ago
  1. SELECT * FROM COMMON_CODE cc ORDER BY CREATED_AT DESC;
    INSERT INTO WASADMIN.COMMON_CODE
    (ID, CODE_GROUP, CODE, VALUE, DEL_YN, CREATED_AT, UPDATED_AT, CODE_ORDER)
    VALUES(199, 'NCSTLOC', '62,123', '성남시 판교동', '0', TIMESTAMP '2023-07-09 07:56:00.874603', TIMESTAMP '2023-07-09 07:56:00.874603', 2);
    INSERT INTO WASADMIN.COMMON_CODE
    (ID, CODE_GROUP, CODE, VALUE, DEL_YN, CREATED_AT, UPDATED_AT, CODE_ORDER)
    VALUES(198, 'NCSTLOC', '60,121', '수원시 화서2동', '0', TIMESTAMP '2023-07-09 07:51:13.514812', TIMESTAMP '2023-07-09 07:56:08.274129', 1);

  2. SELECT * FROM ZTHH_SYSTEMMASTER zs ORDER BY CREATE_DT desc;

  3. SELECT * FROM ZTHH_APIMASTER za ORDER BY CREATE_DT desc;
    INSERT INTO WASADMIN.ZTHH_APIMASTER
    (ID, API_NAME, API_DESCRIPTION, CALL_URL, DIRECTION, AUTHOR, CALL_MAX, HTTP_METHOD, LOG_YN, SYSTEM_NAME, DEL_YN, CREATE_ID, CREATE_DT, UPDATE_ID, UPDATE_DT)
    VALUES('apiMaster_50444984-6379-4322-8601-0213e380e324', 'getUltraSrtNcst', '실황정보를 조회하기 위해 발표일자, 발표시각, 예보지점 X 좌표, 예보지점 Y 좌표의 조회 조건으로 자료구분코드, 실황값, 발표일자, 발표시각, 예보지점 X 좌표, 예보지점 Y 좌표의 정보를 조회하는 기능', 'https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getUltraSrtNcst', 'OUT', 'G8dsIOIinqIgxBio8kv6qyrYJ9OsQr%2F5PhyVheRm9NbJfGNNYQSUSKYZH%2BRlgmYs01YxjwihIRUKKyQE1j%2FO%2Fw%3D%3D', 1000, 'GET', 'Y', 'PublicPortal', 'N', '박용완', TIMESTAMP '2023-07-09 06:07:55.817510', '박용완', TIMESTAMP '2023-07-09 06:07:55.817510');

  4. SELECT * FROM ZTHH_MENU zm ORDER BY CREATE_DT desc;
    INSERT INTO WASADMIN.ZTHH_MENU
    (ID, CATEGORY, MENU_LEVEL, MENU_ID, MENU_PATH, MENU_ICON, MENU_ORDER, PARENT_MENU_ID, DEL_YN, CREATE_ID, CREATE_DT, UPDATE_ID, UPDATE_DT, MENU_AUTH)
    VALUES('menu_051d1398-ba17-4576-b208-a0e183df8204', 'Interface', 2, 'getUltraSrtNcst', '/getUltraSrtNcst/list', 'N/A', 5, 'layout', 'N', NULL, TIMESTAMP '2023-07-09 08:22:20.039170', NULL, TIMESTAMP '2023-07-09 08:22:20.039170', 'ROLE_ANY');

  5. SELECT * FROM ZTHH_MENUCONTROL zm ORDER BY CREATE_DT desc;
    
    INSERT INTO WASADMIN.ZTHH_MENUCONTROL
    (ID, URL, "METHOD", ROLE_ID, DEL_YN, CREATE_ID, CREATE_DT, UPDATE_ID, UPDATE_DT, LOG_YN, LOG_DATA_YN)
    VALUES('menuControl_966add4b-9e77-4a5e-b50f-e5f5bf937639', '/getUltraSrtNcst/list', 'GET', 'ANY', 'N', '박용완', TIMESTAMP '2023-07-09 08:42:05.926957', '박용완', TIMESTAMP '2023-07-09 08:42:05.926957', 'Y', 'N');

INSERT INTO WASADMIN.ZTHH_MENUCONTROL (ID, URL, "METHOD", ROLE_ID, DEL_YN, CREATE_ID, CREATE_DT, UPDATE_ID, UPDATE_DT, LOG_YN, LOG_DATA_YN) VALUES('menuControl_664a7f23-b406-4194-aedf-a38684f0c2e9', '/getUltraSrtNcst/list', 'POST', 'ANY', 'N', '박용완', TIMESTAMP '2023-07-09 08:52:38.239179', '박용완', TIMESTAMP '2023-07-09 08:52:38.239179', 'Y', 'N');

INSERT INTO WASADMIN.ZTHH_MENUCONTROL (ID, URL, "METHOD", ROLE_ID, DEL_YN, CREATE_ID, CREATE_DT, UPDATE_ID, UPDATE_DT, LOG_YN, LOG_DATA_YN) VALUES('menuControl_fd535347-c4cb-425a-a93f-4aed31af341f', '/commonCode/NCSTLOC', 'GET', 'ANY', 'N', '박용완', TIMESTAMP '2023-07-09 08:42:07.184598', '박용완', TIMESTAMP '2023-07-09 08:42:07.184598', 'Y', 'N');

eunja511005 commented 12 months ago

image