From 3114277626737b76d66a882e7699e37220bc5ee3 Mon Sep 17 00:00:00 2001 From: limju Date: Thu, 2 Nov 2023 13:27:27 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20post=20plus=20=EC=A0=81=EC=9A=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../xit/ens/pplus/service/PplusService.java | 30 +- .../java/kr/xit/ens/pplus/web/ApiExample.java | 256 ++++++++++++++++++ .../biz/ens/service/EnsBatchSendService.java | 102 ++----- .../kr/xit/biz/ens/model/pplus/PplusDTO.java | 4 + 4 files changed, 302 insertions(+), 90 deletions(-) create mode 100644 mens-api/src/main/java/kr/xit/ens/pplus/web/ApiExample.java diff --git a/mens-api/src/main/java/kr/xit/ens/pplus/service/PplusService.java b/mens-api/src/main/java/kr/xit/ens/pplus/service/PplusService.java index 5f78229..2f65049 100644 --- a/mens-api/src/main/java/kr/xit/ens/pplus/service/PplusService.java +++ b/mens-api/src/main/java/kr/xit/ens/pplus/service/PplusService.java @@ -1,6 +1,7 @@ package kr.xit.ens.pplus.service; -import java.nio.charset.StandardCharsets; +import java.io.FileWriter; +import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -11,6 +12,7 @@ import kr.xit.biz.ens.model.pplus.PplusDTO.BatchAcceptRequest; import kr.xit.biz.ens.model.pplus.PplusDTO.PpCommonResponse; import kr.xit.biz.ens.model.pplus.PplusDTO.PpStatusRequest; import kr.xit.biz.ens.model.pplus.PplusDTO.PpStatusResponse; +import kr.xit.core.exception.BizRuntimeException; import kr.xit.core.spring.util.ApiWebClientUtil; import kr.xit.core.support.utils.FileUtil; import kr.xit.core.support.utils.JsonUtils; @@ -84,27 +86,43 @@ public class PplusService extends EgovAbstractServiceImpl implements IPplusServi pstJson.put("master", master); pstJson.put("detail", detail); - accept(reqDTO, pstJson); + try (FileWriter pstFile = new FileWriter(FILE_TEMP_PATH + "/" + "pstFile.json")) { + pstFile.write(JsonUtils.jsonEnterConvert(pstJson)); + pstFile.flush(); + } catch (IOException ie){ + throw BizRuntimeException.create(ie.getMessage()); + } + accept(reqDTO, pstJson, tgtList.get(0).getUnitySndngMastrId()); } return null; } //@TraceLogging - private PpCommonResponse accept(final SndngMssageParam paramDTO, final JSONObject jsonObj) { + private PpCommonResponse accept(final SndngMssageParam paramDTO, final JSONObject jsonObj, final String unitySndngMstId) { final CmmEnsRlaybsnmDTO ktMnsInfo = CmmKtMmsUtils.getRlaybsnmInfo(paramDTO.getSignguCode(), paramDTO.getFfnlgCode()); - - FileUtil.saveFile(FILE_TEMP_PATH,"pstFile.json", jsonObj.toJSONString().getBytes(StandardCharsets.UTF_8)); +/* + try (FileWriter pstFile = new FileWriter(FILE_TEMP_PATH + "/" + "pstFile.json")) { + pstFile.write(jsonObj.toJSONString()); + pstFile.flush(); + } catch (IOException ie){ + throw BizRuntimeException.create(ie.getMessage()); + } + */ + //FileUtil.saveFile(FILE_TEMP_PATH,"pstFile.json", jsonObj.toJSONString().getBytes(StandardCharsets.UTF_8)); MultipartFile pstFile = FileUtil.createMutipartFile("pstFile.json", FILE_TEMP_PATH); List pstFiles = new ArrayList<>(); pstFiles.add(pstFile); - return webClient.exchangeFileData( + PpCommonResponse resDTO = webClient.exchangeFileData( HOST + ACCEPT + String.format("?apiKey=%s", ktMnsInfo.getPplusApiKey()), HttpMethod.POST, pstFiles, PpCommonResponse.class ); + resDTO.setUnitySndngMastrId(unitySndngMstId); + + return resDTO; } @Override diff --git a/mens-api/src/main/java/kr/xit/ens/pplus/web/ApiExample.java b/mens-api/src/main/java/kr/xit/ens/pplus/web/ApiExample.java new file mode 100644 index 0000000..3aee298 --- /dev/null +++ b/mens-api/src/main/java/kr/xit/ens/pplus/web/ApiExample.java @@ -0,0 +1,256 @@ +package kr.xit.ens.pplus.web; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import kr.xit.core.exception.BizRuntimeException; +import kr.xit.core.model.ApiResponseDTO; +import kr.xit.core.model.IApiResponse; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@Tag(name = "ApiExample", description = "Postplus(포스토피아) sample API") +@RestController +@RequestMapping("/api/ens/pplus/v1") +public class ApiExample { + + private String charset = "utf-8"; + private final String boundary = "===" + System.currentTimeMillis() + "==="; + private static final String LINE_FEED = "\r\n"; + + + @Operation(summary = "우편제작접수 샘플", description = "우편제작접수 샘플") + @PostMapping(value = "/apiExample", produces = MediaType.APPLICATION_JSON_VALUE) + public IApiResponse apiExample() { + + // master + JSONArray masterCols = new JSONArray(); + masterCols.add("버전"); + masterCols.add("테스트여부"); + masterCols.add("서비스"); + masterCols.add("연계식별키"); + masterCols.add("봉투"); + masterCols.add("봉투창"); + masterCols.add("흑백칼라"); + masterCols.add("단면양면"); + masterCols.add("배달"); + masterCols.add("템플릿코드"); + masterCols.add("템플릿출력여부"); + masterCols.add("수취인수"); + masterCols.add("여백생성유무"); + masterCols.add("주소페이지유무"); + masterCols.add("맞춤자제유무"); + masterCols.add("메일머지유무"); + masterCols.add("동봉물유무"); + masterCols.add("반송여부"); + masterCols.add("스테이플러유무"); + masterCols.add("로고파일"); + masterCols.add("발송인명"); + masterCols.add("발송인우편번호"); + masterCols.add("발송인주소"); + masterCols.add("발송인상세주소"); + masterCols.add("발송인전화번호"); + + JSONArray masterRows = new JSONArray(); + masterRows.add("v1.10"); + masterRows.add("Y"); + masterRows.add("PST"); + masterRows.add("POST20230428_000001"); + masterRows.add("소봉투"); + masterRows.add("이중창"); + masterRows.add("흑백"); + masterRows.add("단면"); + masterRows.add("일반"); + masterRows.add(""); + masterRows.add("N"); + masterRows.add(2); + masterRows.add("N"); + masterRows.add("N"); + masterRows.add("N"); + masterRows.add("N"); + masterRows.add("N"); + masterRows.add("N"); + masterRows.add("N"); + masterRows.add("N"); + masterRows.add("포스토피아"); + masterRows.add("05048"); + masterRows.add("서울특별시 광진구 강변역로2"); + masterRows.add("서울광진우체국 B동 4층"); + masterRows.add("1577-8114"); + + JSONObject master = new JSONObject(); + master.put("cols", masterCols); + master.put("rows", masterRows); + + + // detail + JSONArray detailCols = new JSONArray(); + detailCols.add("순번"); + detailCols.add("이름"); + detailCols.add("우편번호"); + detailCols.add("주소"); + detailCols.add("상세주소"); + detailCols.add("전화번호"); + detailCols.add("첨부파일"); + detailCols.add("가변1"); + detailCols.add("가변2"); + detailCols.add("가변3"); + detailCols.add("가변4"); + + JSONArray detailRows1 = new JSONArray(); + detailRows1.add("1"); + detailRows1.add("홍길동1"); + detailRows1.add("31010"); + detailRows1.add("서울특별시 광진구 강변역로2"); + detailRows1.add("서울광진우체국 B동 1층"); + detailRows1.add("01012341234"); + detailRows1.add("pstFile.pdf"); + detailRows1.add("24926737"); + detailRows1.add("2021-09-02"); + detailRows1.add("대출(고정)"); + detailRows1.add("31,000,000"); + + JSONArray detailRows2 = new JSONArray(); + detailRows2.add("2"); + detailRows2.add("홍길동2"); + detailRows2.add("08394"); + detailRows2.add("서울특별시 광진구 강변역로2"); + detailRows2.add("서울광진우체국 B동 2층"); + detailRows2.add("01012341234"); + detailRows2.add("pstFile.pdf"); + detailRows2.add("25685047"); + detailRows2.add("2021-09-02"); + detailRows2.add("대출B(변동)"); + detailRows2.add("421,000,000"); + + JSONArray detailRows = new JSONArray(); + detailRows.add(detailRows1); + detailRows.add(detailRows2); + + JSONObject detail = new JSONObject(); + detail.put("cols", detailCols); + detail.put("rows", detailRows); + + JSONObject pst = new JSONObject(); + pst.put("master", master); + pst.put("detail", detail); + + // 파일생성 & 저장 + try { + FileWriter pstFile = new FileWriter("d:/data/temp/pstFile2.json"); + pstFile.write(pst.toJSONString()); + pstFile.flush(); + pstFile.close(); + } catch (IOException e) { + e.printStackTrace(); + } + + // API 전송 + URL url = null; + HttpURLConnection conn; + try { + url = new URL("https://t.postplus.co.kr/po/api/postplusPstMsrApi.do"); + //url = new URL("http://localhost:8081/api/ens/pplus/v1/accept2"); + //url = new URL("http://localhost:8081/api/ens/pplus/v1/accept3"); + conn = (HttpURLConnection) url.openConnection(); + conn.setUseCaches(false); + conn.setDoOutput(true); + conn.setDoInput(true); + conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); + conn.setRequestProperty("User-Agent", "CodeJava Agent"); + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } catch (IOException e) { + throw new RuntimeException(e); + } + + + + try (OutputStream ops = conn.getOutputStream(); + PrintWriter writer = new PrintWriter(new OutputStreamWriter(ops, charset), true)) { + //File pstFile = new File("c:/Temp/pstFile.json"); + File pstFile = new File("d:/data/temp/pstFile2.json"); + //File attchFile = new File("c:/Temp/pstFile.pdf"); + + addParam(writer, "apiKey", "00197D16F7FE4A84E9C97F55033339FBE07FB374D7C8C94EE4C96BA7D997297AC1E9CB5F1FC50CC3C63F5285923FDAB73679A011D40CA00CE589C98858AEFFE7F64E8E0FCF59EF0DC52B548C13D16FC2BB4"); + addFile(writer, ops, "pstFile", pstFile); + //addFile(writer, ops, "pstFile", attchFile); + + writer.append("--" + boundary + "--").append(LINE_FEED); + writer.append(LINE_FEED).flush(); + } catch (Exception e){ + throw BizRuntimeException.create(e); + } + + StringBuffer response = new StringBuffer(); + try { + int status = conn.getResponseCode(); + if (status == HttpURLConnection.HTTP_OK) { + try (BufferedReader reader = new BufferedReader( + new InputStreamReader(conn.getInputStream()))) { + String line; + while((line = reader.readLine()) != null) { + response.append(line); + } + } catch (IOException e) { + throw BizRuntimeException.create(e); + } + conn.disconnect(); + } else { + throw BizRuntimeException.create("Server returned non-OK status: " + status); + } + } catch (IOException e) { + throw BizRuntimeException.create(e); + } + return ApiResponseDTO.success(response.toString()); + } + + private void addParam(PrintWriter writer, String name, String value) { + writer.append("--" + boundary).append(LINE_FEED); + writer.append("Content-Disposition: form-data; name=\"" + name + "\"").append(LINE_FEED); + writer.append("Content-Type: text/plain; charset=" + charset).append(LINE_FEED); + writer.append(LINE_FEED); + writer.append(value).append(LINE_FEED); + writer.flush(); + } + + private void addFile(PrintWriter writer, OutputStream ops, String name, File uploadFile) { + String fileName = uploadFile.getName(); + writer.append("--" + boundary).append(LINE_FEED); + writer.append("Content-Disposition: form-data; name=\"" + name+ "\"; filename=\"" + fileName + "\"").append(LINE_FEED); + writer.append("Content-Type: "+ URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED); + writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED); + writer.append(LINE_FEED); + writer.flush(); + + try (FileInputStream is = new FileInputStream(uploadFile)) { + byte[] buffer = new byte[4096]; + int bytesRead = -1; + while((bytesRead = is.read(buffer)) != -1) { + ops.write(buffer, 0, bytesRead); + } + ops.flush(); + } catch (IOException e){ + throw BizRuntimeException.create(e.getMessage()); + } + writer.append(LINE_FEED); + writer.flush(); + } +} + diff --git a/mens-batch/src/main/java/kr/xit/biz/ens/service/EnsBatchSendService.java b/mens-batch/src/main/java/kr/xit/biz/ens/service/EnsBatchSendService.java index eb9a4f0..96cd2b4 100644 --- a/mens-batch/src/main/java/kr/xit/biz/ens/service/EnsBatchSendService.java +++ b/mens-batch/src/main/java/kr/xit/biz/ens/service/EnsBatchSendService.java @@ -26,12 +26,14 @@ import kr.xit.biz.ens.model.kakao.KkopayDocBulkDTO.PropertyBulk; import kr.xit.biz.ens.model.kt.KtCommonDTO.ErrorMsg; import kr.xit.biz.ens.model.kt.KtCommonDTO.KtCommonResponse; import kr.xit.biz.ens.model.kt.KtMmsSendDTO.KtMainSendReqData; +import kr.xit.biz.ens.model.pplus.PplusDTO.PpCommonResponse; import kr.xit.core.exception.BizRuntimeException; import kr.xit.core.model.ApiResponseDTO; import kr.xit.core.spring.util.ApiWebClientUtil; import kr.xit.core.support.utils.Checks; import kr.xit.core.support.utils.DateUtils; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.ListUtils; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; @@ -59,6 +61,7 @@ import org.springframework.transaction.annotation.Transactional; * * */ +@Slf4j @RequiredArgsConstructor @Service public class EnsBatchSendService extends EgovAbstractServiceImpl implements IEnsBatchSendService { @@ -440,101 +443,32 @@ public class EnsBatchSendService extends EgovAbstractServiceImpl implements IEns private void sendBulkPplus(final SndngMssageParam dto) { final String url = apiHost + apiPplusBulkSend; - ApiResponseDTO responseDTO = apiWebClient.exchange( + ApiResponseDTO apiResult = apiWebClient.exchange( url, HttpMethod.POST, dto, ApiResponseDTO.class, CmmEnsBizUtils.getHeadeMap()); + final String mstId = dto.getSndngMastrId(); + if(ObjectUtils.isNotEmpty(apiResult.getData())) { + PpCommonResponse resDTO = toObjByObj(apiResult.getData(), PpCommonResponse.class); + assert resDTO != null; + if(ObjectUtils.isNotEmpty(resDTO) && "OK".equals(resDTO.get결과())){ + extractService.updateSendSndngMstStatus(mstId, resDTO.getUnitySndngMastrId(), SndngSeCode.KT_BC, "KT-BC 실패(발송마스터 데이타 오류)"); + return; + } + extractService.updateSndngMstFailStatus(mstId, SndngSeCode.PPLUS, "[send] Post Plus 발송(Accept)요청 실패"); -// -// PpAcceptRequestStruct reqDataDTO = PpAcceptRequestStruct.builder() -// .master(PpAcceptReqDataStruct.builder() -// .cols(JsonUtils.toJson(mstJson.get("cols"))) -// .rows(JsonUtils.toJson(mstJson.get("rows"))) -// .build()) -// .detail(PpAcceptReqDataStruct.builder() -// .cols(JsonUtils.toJson(dtlJson.get("cols"))) -// .rows(JsonUtils.toJson(dtlJson.get("rows"))) -// .build()) -// .build(); -// -// String reqDataJsonStr = JsonUtils.toJson(reqDataDTO); -// -// -// // validation check -// try { -// validatedKtBcSendBulks(sendReqs); -// } catch (Exception e) { -// extractService.updateSndngMstFailStatus(mstId, SndngSeCode.KT_BC, "[send]KT-BC 발송(bulks)요청 실패(파라메터 오류)"); -// throw e; -// } -// -// final List> partitions = ListUtils.partition(sendReqs, bulkKtMaxCnt); -// List apiResults = partitions.stream() -// .map(bulkSendList -> { -// mstDTO.setReqs(bulkSendList); -// return apiWebClient.exchange( -// url, -// HttpMethod.POST, -// mstDTO, -// ApiResponseDTO.class, -// CmmEnsBizUtils.getHeadeMap()); -// } -// ) -// .toList(); -// -// boolean isSuccess = false; -// List errList = new ArrayList<>(); -// for(ApiResponseDTO apiResult : apiResults) { -// // KT-BC API 정상 호출 -// if(ObjectUtils.isNotEmpty(apiResult.getData())) { -// KtCommonResponse resDTO = toObjByObj(apiResult.getData(), KtCommonResponse.class); -// assert resDTO != null; -// dto.setResultDt(resDTO.getResultDt()); -// -// if(ObjectUtils.isNotEmpty(resDTO) && "00".equals(resDTO.getResultCd())){ -// isSuccess = true; -// dto.setErrorMssage("정상"); -// }else{ -// errList.addAll(resDTO.getErrors()); -// } -// -// }else{ -// // KT-BC API 호출전 에러 발생 -// if(ObjectUtils.isEmpty(dto.getResultDt())) { -// dto.setResultDt(DateUtils.getTodayAndNowTime(ApiConstants.FMT_DT_EMPTY_DLT)); -// } -// dto.setErrorMssage(apiResult.getMessage()); -// errList.add(new ErrorMsg(apiResult.getMessage())); -// } -// } -// -// // 모두 실패한 경우 -// if(!isSuccess) { -// dto.setResultCd("01"); -// dto.setErrorMssage( -// errList.stream() -// .map(ErrorMsg::getErrorMsg) -// .collect(Collectors.joining(",")) -// ); -// mapper.updateKtBcMst(dto); -// extractService.updateSndngMstFailStatus(mstId, SndngSeCode.KT_BC, "[send] KT-BC 발송(bulks)요청 실패"); -// return; -// } -// -// // 성공 건수 존재시 성공 처리 -// dto.setResultCd("00"); -// dto.setErrorMssage("정상"); -// mapper.updateKtBcMst(dto); -// extractService.updateSendSndngMstStatus(mstId, unitySndMstId, SndngSeCode.KAKAO, "KT-BC 실패(발송마스터 데이타 오류)"); -// -// extractService.sendPostPlus(tgtDTO); + }else{ + //extractService.updateSndngMstFailStatus(mstId, SndngSeCode.PPLUS, "[send] Post Plus 발송(Accept)요청 실패"); + log.error("\n\n\n\n\n#################~~~ ??? 발생할 수 없는 경우 인데 ??? ~~~######################################################"); + throw BizRuntimeException.create("~~~ ??? 발생할 수 없는 경우 인데 ??? ~~~"); + } } //----------------------------------------------------------------------------------------------------------------- } diff --git a/mens-core/src/main/java/kr/xit/biz/ens/model/pplus/PplusDTO.java b/mens-core/src/main/java/kr/xit/biz/ens/model/pplus/PplusDTO.java index efe67ed..3387b3d 100644 --- a/mens-core/src/main/java/kr/xit/biz/ens/model/pplus/PplusDTO.java +++ b/mens-core/src/main/java/kr/xit/biz/ens/model/pplus/PplusDTO.java @@ -12,6 +12,7 @@ import lombok.Data; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; +import lombok.Setter; import lombok.experimental.SuperBuilder; import org.apache.commons.lang3.StringUtils; import org.hibernate.validator.constraints.NotEmpty; @@ -68,6 +69,9 @@ public class PplusDTO { */ @Schema(requiredMode = RequiredMode.REQUIRED) private String 비고; + + @Setter + private String unitySndngMastrId; } /**