From dccf7a2fb7fc5f27b1bb34af151ef8de51933e90 Mon Sep 17 00:00:00 2001 From: limju Date: Tue, 12 Sep 2023 18:10:40 +0900 Subject: [PATCH] =?UTF-8?q?refactor:=20API=EC=97=90=EC=84=9C=20batch?= =?UTF-8?q?=EB=AA=A8=EB=93=88=20=EC=A0=9C=EA=B1=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- mens-api/pom.xml | 13 + .../biz/batch/CustomRunIdIncrementer.java | 38 --- .../kr/xit/core/biz/batch/ListReader.java | 37 --- .../batch/listener/CustomChunkListener.java | 48 ---- .../biz/batch/listener/CustomItemListner.java | 29 -- .../biz/batch/listener/CustomJobListener.java | 41 --- .../batch/listener/CustomStepListener.java | 40 --- .../listener/NoWorkFoundStepListener.java | 16 -- .../biz/batch/mapper/IBatchCmmMapper.java | 32 --- .../xit/core/biz/batch/model/BatchCmmDTO.java | 68 ----- .../biz/batch/service/BatchCmmService.java | 65 ----- .../biz/batch/service/IBatchCmmService.java | 29 -- .../core/biz/batch/task/BatchEndTasklet.java | 57 ---- .../biz/batch/task/BatchFailEndTasklet.java | 59 ---- .../biz/batch/task/BatchStartTasklet.java | 75 ----- .../config/support/PrimaryMybatisConfig.java | 6 +- .../xit/core/spring/util/ApiSpringUtils.java | 1 - .../ens/support/cmm/mapper/ICmmEnsMapper.java | 27 ++ .../cmm/service/CmmEnsCacheService.java | 60 ++++ .../cmm/service/ICmmEnsCacheService.java | 28 ++ .../support/nice/service/INiceCiService.java | 11 + .../nice/service/NiceCiDummyTestService.java | 34 ++- .../support/nice/service/NiceCiService.java | 189 +++++++++++-- .../support/nice/web/NiceCiController.java | 21 +- .../nice/web/NiceCiDummyTestController.java | 5 +- .../main/resources/config/application-ens.yml | 5 +- .../mapper/biz/IKkoMyDocMapper.xml | 17 -- .../mapper/biz/ens-mysql-mapper.xml | 18 ++ .../mapper/core/cmm-batch-mysql-mapper.xml | 68 ----- .../config/support/PrimaryMybatisConfig.java | 6 +- .../java/kr/xit/biz/common}/AuditFields.java | 9 +- .../kr/xit/biz/ens/model/nice/NiceCiDTO.java | 259 +++++++++++++++++- .../xit/core/support/utils/SecureUtils.java | 12 + 33 files changed, 635 insertions(+), 788 deletions(-) delete mode 100644 mens-api/src/main/java/kr/xit/core/biz/batch/CustomRunIdIncrementer.java delete mode 100644 mens-api/src/main/java/kr/xit/core/biz/batch/ListReader.java delete mode 100644 mens-api/src/main/java/kr/xit/core/biz/batch/listener/CustomChunkListener.java delete mode 100644 mens-api/src/main/java/kr/xit/core/biz/batch/listener/CustomItemListner.java delete mode 100644 mens-api/src/main/java/kr/xit/core/biz/batch/listener/CustomJobListener.java delete mode 100644 mens-api/src/main/java/kr/xit/core/biz/batch/listener/CustomStepListener.java delete mode 100644 mens-api/src/main/java/kr/xit/core/biz/batch/listener/NoWorkFoundStepListener.java delete mode 100644 mens-api/src/main/java/kr/xit/core/biz/batch/mapper/IBatchCmmMapper.java delete mode 100644 mens-api/src/main/java/kr/xit/core/biz/batch/model/BatchCmmDTO.java delete mode 100644 mens-api/src/main/java/kr/xit/core/biz/batch/service/BatchCmmService.java delete mode 100644 mens-api/src/main/java/kr/xit/core/biz/batch/service/IBatchCmmService.java delete mode 100644 mens-api/src/main/java/kr/xit/core/biz/batch/task/BatchEndTasklet.java delete mode 100644 mens-api/src/main/java/kr/xit/core/biz/batch/task/BatchFailEndTasklet.java delete mode 100644 mens-api/src/main/java/kr/xit/core/biz/batch/task/BatchStartTasklet.java create mode 100644 mens-api/src/main/java/kr/xit/ens/support/cmm/mapper/ICmmEnsMapper.java create mode 100644 mens-api/src/main/java/kr/xit/ens/support/cmm/service/CmmEnsCacheService.java create mode 100644 mens-api/src/main/java/kr/xit/ens/support/cmm/service/ICmmEnsCacheService.java delete mode 100644 mens-api/src/main/resources/egovframework/mapper/biz/IKkoMyDocMapper.xml create mode 100644 mens-api/src/main/resources/egovframework/mapper/biz/ens-mysql-mapper.xml delete mode 100644 mens-api/src/main/resources/egovframework/mapper/core/cmm-batch-mysql-mapper.xml rename {mens-api/src/main/java/kr/xit/core/biz/model => mens-core/src/main/java/kr/xit/biz/common}/AuditFields.java (92%) diff --git a/mens-api/pom.xml b/mens-api/pom.xml index 08c3b1b..665a729 100644 --- a/mens-api/pom.xml +++ b/mens-api/pom.xml @@ -83,6 +83,19 @@ spring-boot-starter-jta-atomikos + + + org.springframework.boot + spring-boot-starter-cache + + + com.github.ben-manes.caffeine + caffeine + + + + + diff --git a/mens-api/src/main/java/kr/xit/core/biz/batch/CustomRunIdIncrementer.java b/mens-api/src/main/java/kr/xit/core/biz/batch/CustomRunIdIncrementer.java deleted file mode 100644 index 5934565..0000000 --- a/mens-api/src/main/java/kr/xit/core/biz/batch/CustomRunIdIncrementer.java +++ /dev/null @@ -1,38 +0,0 @@ -package kr.xit.core.biz.batch; - -import org.springframework.batch.core.JobParameters; -import org.springframework.batch.core.JobParametersBuilder; -import org.springframework.batch.core.launch.support.RunIdIncrementer; - -/** - *
- * description :  Spring Boot 2.0.x에서 발생하는 버그
- *                => 배치 Job이 실패할 경우 이후에 파라미터를 변경해도 계속 실패한 파라미터가 사용
- *                Spring Boot 2.1.0 이상부터는
- *                => 이전의 Job이 실행시 사용한 파라미터 중 하나가 다음 실행시 누락되면 누락된 파라미터를 재사용
- *                   --> 넘어온 파라미터와 run.id만 사용
- *                  .incrementer(new RunIdIncrementer()) -> .incrementer(new UniqueRunIdIncrementer())
- *
- * packageName : kr.xit.core.biz.batch
- * fileName    : CustomRunIdIncrementer
- * author      : limju
- * date        : 2023-05-16
- * ======================================================================
- * 변경일         변경자        변경 내용
- * ----------------------------------------------------------------------
- * 2023-05-16    limju       최초 생성
- *
- * 
- */ -public class CustomRunIdIncrementer extends RunIdIncrementer { - private static final String RUN_ID = "run.id"; - - @Override - public JobParameters getNext(JobParameters parameters) { - JobParameters params = (parameters == null) ? new JobParameters() : parameters; - return new JobParametersBuilder() - .addLong(RUN_ID, params.getLong(RUN_ID, 0L) + 1) - .toJobParameters(); - } -} - diff --git a/mens-api/src/main/java/kr/xit/core/biz/batch/ListReader.java b/mens-api/src/main/java/kr/xit/core/biz/batch/ListReader.java deleted file mode 100644 index 4eb7492..0000000 --- a/mens-api/src/main/java/kr/xit/core/biz/batch/ListReader.java +++ /dev/null @@ -1,37 +0,0 @@ -package kr.xit.core.biz.batch; - -import java.util.List; - -/** - *
- * description : ItemReaderAdapter 를 사용한 List 데이타의 read() 구현
- *               -> ItemReader 의 read
- *               ItemReaderAdapter의 targetObject 지정시 사용
- *               -> ItemReaderAdapter.setTargetObject(Object o)
- *                  : new ListReader<>(대상목록-서비스 조회결과)
- *                  : new ListReader<>(loggingService.findLogging(null))
- * packageName : kr.xit.core.biz.batch
- * fileName    : ListReader
- * author      : limju
- * date        : 2023-05-16
- * ======================================================================
- * 변경일         변경자        변경 내용
- * ----------------------------------------------------------------------
- * 2023-05-16    limju       최초 생성
- *
- * 
- */ -public class ListReader { - private List list; - - public ListReader(List list){ - this.list = list; - } - - public T read() { - if(list.isEmpty()){ - return null; - } - return list.remove(0); - } - } diff --git a/mens-api/src/main/java/kr/xit/core/biz/batch/listener/CustomChunkListener.java b/mens-api/src/main/java/kr/xit/core/biz/batch/listener/CustomChunkListener.java deleted file mode 100644 index cfa4e91..0000000 --- a/mens-api/src/main/java/kr/xit/core/biz/batch/listener/CustomChunkListener.java +++ /dev/null @@ -1,48 +0,0 @@ -package kr.xit.core.biz.batch.listener; - -import org.springframework.batch.core.ChunkListener; -import org.springframework.batch.core.scope.context.ChunkContext; -import org.springframework.context.annotation.Bean; -import org.springframework.stereotype.Component; - -import lombok.extern.slf4j.Slf4j; - -/** - *
- * description :  Chunk 실행시 로그 출력
- *
- * packageName : kr.xit.core.biz.batch.listener
- * fileName    : CustomChunkListener
- * author      : limju
- * date        : 2023-05-16
- * ======================================================================
- * 변경일         변경자        변경 내용
- * ----------------------------------------------------------------------
- * 2023-05-16    limju       최초 생성
- *
- * 
- */ -@Slf4j -@Component -public class CustomChunkListener { - - @Bean - public ChunkListener chunkListener() { - return new ChunkListener() { - @Override - public void beforeChunk(ChunkContext context) { - log.info("↓ Chunk start"); - } - - @Override - public void afterChunk(ChunkContext context) { - log.info("↑ Chunk end"); - } - - @Override - public void afterChunkError(ChunkContext context) { - // Do nothing - } - }; - } -} diff --git a/mens-api/src/main/java/kr/xit/core/biz/batch/listener/CustomItemListner.java b/mens-api/src/main/java/kr/xit/core/biz/batch/listener/CustomItemListner.java deleted file mode 100644 index 785edf1..0000000 --- a/mens-api/src/main/java/kr/xit/core/biz/batch/listener/CustomItemListner.java +++ /dev/null @@ -1,29 +0,0 @@ -package kr.xit.core.biz.batch.listener; - -import java.util.List; - -import org.springframework.batch.core.listener.ItemListenerSupport; - -import lombok.extern.slf4j.Slf4j; - -@Slf4j -public class CustomItemListner extends ItemListenerSupport { - - public void onReadError(Exception ex) { - log.error("onReadError", ex); - } - - @Override - public void onProcessError(Object item, Exception e) { - log.error("onProcessError", e); - super.onProcessError(item, e); - } - - @Override - public void onWriteError(Exception ex, List item) { - log.error("onWriteError", ex); - } - - - -} diff --git a/mens-api/src/main/java/kr/xit/core/biz/batch/listener/CustomJobListener.java b/mens-api/src/main/java/kr/xit/core/biz/batch/listener/CustomJobListener.java deleted file mode 100644 index 5af0a8f..0000000 --- a/mens-api/src/main/java/kr/xit/core/biz/batch/listener/CustomJobListener.java +++ /dev/null @@ -1,41 +0,0 @@ -package kr.xit.core.biz.batch.listener; - -import org.springframework.batch.core.JobExecution; -import org.springframework.batch.core.listener.JobExecutionListenerSupport; - -import lombok.extern.slf4j.Slf4j; - -/** - *
- * description :  Job 실행시 로그 출력
- *
- * packageName : kr.xit.core.biz.batch.listener
- * fileName    : CustomJobListener
- * author      : limju
- * date        : 2023-05-16
- * ======================================================================
- * 변경일         변경자        변경 내용
- * ----------------------------------------------------------------------
- * 2023-05-16    limju       최초 생성
- *
- * 
- */ -@Slf4j -public class CustomJobListener extends JobExecutionListenerSupport { - - @Override - public void beforeJob(JobExecution jobExecution) { - log.info("\n"); - log.info("===================================================="); - log.info("========== ↓ [{}] Job start ===========", jobExecution.getJobInstance().getJobName()); - log.info("===================================================="); - } - - @Override - public void afterJob(JobExecution jobExecution) { - log.info("==============================================================="); - log.info("========== ↑ [{}] Job end :: {} ==========", jobExecution.getJobInstance().getJobName(), jobExecution.getStatus()); - log.info("==============================================================="); - log.info("\n"); - } -} diff --git a/mens-api/src/main/java/kr/xit/core/biz/batch/listener/CustomStepListener.java b/mens-api/src/main/java/kr/xit/core/biz/batch/listener/CustomStepListener.java deleted file mode 100644 index 3606a4a..0000000 --- a/mens-api/src/main/java/kr/xit/core/biz/batch/listener/CustomStepListener.java +++ /dev/null @@ -1,40 +0,0 @@ -package kr.xit.core.biz.batch.listener; - -import org.springframework.batch.core.ExitStatus; -import org.springframework.batch.core.StepExecution; -import org.springframework.batch.core.StepExecutionListener; -import org.springframework.batch.core.listener.StepExecutionListenerSupport; - -import lombok.extern.slf4j.Slf4j; - -/** - *
- * description :  step 실행시 로그 출력
- *
- * packageName : kr.xit.core.biz.batch.listener
- * fileName    : CustomStepListener
- * author      : limju
- * date        : 2023-05-16
- * ======================================================================
- * 변경일         변경자        변경 내용
- * ----------------------------------------------------------------------
- * 2023-05-16    limju       최초 생성
- *
- * 
- */ -@Slf4j -public class CustomStepListener extends StepExecutionListenerSupport { - - @Override - public void beforeStep(StepExecution stepExecution) { - log.info("##### ↓ [{}] Step start", stepExecution.getStepName()); - //log.info("##### [{}-{}] Step is start", stepExecution.getJobExecution().getJobInstance().getJobName(), stepExecution.getStepName()); - } - - @Override - public ExitStatus afterStep(StepExecution stepExecution) { - log.info("##### ↑ [{}] Step end :: {}", stepExecution.getStepName(), stepExecution.getStatus()); - //log.info("##### [{}-{}] Step is completed {}", stepExecution.getJobExecution().getJobInstance().getJobName(), stepExecution.getStepName(), stepExecution.getStatus()); - return stepExecution.getExitStatus(); - } -} diff --git a/mens-api/src/main/java/kr/xit/core/biz/batch/listener/NoWorkFoundStepListener.java b/mens-api/src/main/java/kr/xit/core/biz/batch/listener/NoWorkFoundStepListener.java deleted file mode 100644 index 952dd4a..0000000 --- a/mens-api/src/main/java/kr/xit/core/biz/batch/listener/NoWorkFoundStepListener.java +++ /dev/null @@ -1,16 +0,0 @@ -package kr.xit.core.biz.batch.listener; - -import org.springframework.batch.core.ExitStatus; -import org.springframework.batch.core.StepExecution; -import org.springframework.batch.core.listener.StepExecutionListenerSupport; - -public class NoWorkFoundStepListener extends StepExecutionListenerSupport { - - public ExitStatus afterStep(StepExecution stepExecution) { - if (stepExecution.getReadCount() == 0) { - return ExitStatus.FAILED; - } - return null; - } - -} diff --git a/mens-api/src/main/java/kr/xit/core/biz/batch/mapper/IBatchCmmMapper.java b/mens-api/src/main/java/kr/xit/core/biz/batch/mapper/IBatchCmmMapper.java deleted file mode 100644 index 092d1b3..0000000 --- a/mens-api/src/main/java/kr/xit/core/biz/batch/mapper/IBatchCmmMapper.java +++ /dev/null @@ -1,32 +0,0 @@ -package kr.xit.core.biz.batch.mapper; - -import java.util.Optional; - -import org.egovframe.rte.psl.dataaccess.mapper.Mapper; - -import kr.xit.core.biz.batch.model.BatchCmmDTO; - -/** - *
- * description :
- *
- * packageName : kr.xit.core.biz.batch.mapper
- * fileName    : IBatchCmmMapper
- * author      : limju
- * date        : 2023-05-16
- * ======================================================================
- * 변경일         변경자        변경 내용
- * ----------------------------------------------------------------------
- * 2023-05-16    limju       최초 생성
- *
- * 
- */ -@Mapper -public interface IBatchCmmMapper { - Optional selectBatchLockByInstanceId(final String instanceId); - int insertBatchLock(final BatchCmmDTO dto); - int updateBatchLock(final BatchCmmDTO dto); - - int insertBatchLog(final BatchCmmDTO dto); - int updateBatchLog(final BatchCmmDTO dto); -} diff --git a/mens-api/src/main/java/kr/xit/core/biz/batch/model/BatchCmmDTO.java b/mens-api/src/main/java/kr/xit/core/biz/batch/model/BatchCmmDTO.java deleted file mode 100644 index 5c3087d..0000000 --- a/mens-api/src/main/java/kr/xit/core/biz/batch/model/BatchCmmDTO.java +++ /dev/null @@ -1,68 +0,0 @@ -package kr.xit.core.biz.batch.model; - -import java.time.LocalDateTime; - -import com.fasterxml.jackson.annotation.JsonFormat; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - *
- * description :
- *
- * packageName : kr.xit.core.biz.batch.model
- * fileName    : BatchCmmDTO
- * author      : limju
- * date        : 2023-05-16
- * ======================================================================
- * 변경일         변경자        변경 내용
- * ----------------------------------------------------------------------
- * 2023-05-16    limju       최초 생성
- * 2023-06-15    limju       배치로그 추가
- *
- * 
- */ -@Data -@NoArgsConstructor -@AllArgsConstructor -@Builder -public class BatchCmmDTO { - /** - * 배치 로그 ID - */ - private String batchLogId; - /** - * 배치 인스턴스 ID - */ - private String instanceId; - /** - * 배치 API trace ID - */ - private String traceId; - /** - * 실행 결과 - */ - private String result; - /** - * 에러메세지 - */ - private String message; - /** - * 배치 실행중 여부 - */ - private String useYn; - - //@Convert(converter = Jsr310.LocalDateTimeConverter.class) - @JsonDeserialize(using = LocalDateDeserializer.class) - @JsonFormat(pattern = "yyyy-MM-dd kk:mm:ss.SSS") - private LocalDateTime registDt; - - @JsonDeserialize(using = LocalDateDeserializer.class) - @JsonFormat(pattern = "yyyy-MM-dd kk:mm:ss.SSS") - private LocalDateTime updateDt; -} diff --git a/mens-api/src/main/java/kr/xit/core/biz/batch/service/BatchCmmService.java b/mens-api/src/main/java/kr/xit/core/biz/batch/service/BatchCmmService.java deleted file mode 100644 index 9ebefd9..0000000 --- a/mens-api/src/main/java/kr/xit/core/biz/batch/service/BatchCmmService.java +++ /dev/null @@ -1,65 +0,0 @@ -package kr.xit.core.biz.batch.service; - -import java.util.Optional; - -import org.egovframe.rte.fdl.cmmn.EgovAbstractServiceImpl; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; - -import kr.xit.core.biz.batch.mapper.IBatchCmmMapper; -import kr.xit.core.biz.batch.model.BatchCmmDTO; - -/** - *
- * description :
- *
- * packageName : kr.xit.core.biz.service
- * fileName    : BatchLockService
- * author      : limju
- * date        : 2023-05-18
- * ======================================================================
- * 변경일         변경자        변경 내용
- * ----------------------------------------------------------------------
- * 2023-05-18    limju       최초 생성
- *
- * 
- */ -@Service -public class BatchCmmService extends EgovAbstractServiceImpl implements IBatchCmmService { - private final IBatchCmmMapper mapper; - - public BatchCmmService(IBatchCmmMapper mapper) { - this.mapper = mapper; - } - - @Override - @Transactional(readOnly = true) - public Optional findById(final String instanceId) { - return mapper.selectBatchLockByInstanceId(instanceId); - } - - @Override - @Transactional(propagation = Propagation.REQUIRES_NEW) - public void addBatchLock(final BatchCmmDTO dto) { - mapper.insertBatchLock(dto); - } - - @Override - @Transactional(propagation = Propagation.REQUIRES_NEW) - public void modifyBatchLock(final BatchCmmDTO dto) { - mapper.updateBatchLock(dto); - } - - @Override - @Transactional(propagation = Propagation.REQUIRES_NEW) - public void addBatchLog(final BatchCmmDTO dto) { - mapper.insertBatchLog(dto); - } - - @Override - @Transactional(propagation = Propagation.REQUIRES_NEW) - public void modifyBatchLog(final BatchCmmDTO dto) { - mapper.updateBatchLog(dto); - } -} diff --git a/mens-api/src/main/java/kr/xit/core/biz/batch/service/IBatchCmmService.java b/mens-api/src/main/java/kr/xit/core/biz/batch/service/IBatchCmmService.java deleted file mode 100644 index dbae56d..0000000 --- a/mens-api/src/main/java/kr/xit/core/biz/batch/service/IBatchCmmService.java +++ /dev/null @@ -1,29 +0,0 @@ -package kr.xit.core.biz.batch.service; - -import java.util.Optional; - -import kr.xit.core.biz.batch.model.BatchCmmDTO; - -/** - *
- * description :
- *
- * packageName : kr.xit.core.biz.service
- * fileName    : IBatchCmmService
- * author      : limju
- * date        : 2023-05-18
- * ======================================================================
- * 변경일         변경자        변경 내용
- * ----------------------------------------------------------------------
- * 2023-05-18    limju       최초 생성
- *
- * 
- */ -public interface IBatchCmmService { - Optional findById(final String instanceId); - void addBatchLock(final BatchCmmDTO dto); - void modifyBatchLock(final BatchCmmDTO dto); - - void addBatchLog(final BatchCmmDTO dto); - void modifyBatchLog(final BatchCmmDTO dto); -} diff --git a/mens-api/src/main/java/kr/xit/core/biz/batch/task/BatchEndTasklet.java b/mens-api/src/main/java/kr/xit/core/biz/batch/task/BatchEndTasklet.java deleted file mode 100644 index 5641426..0000000 --- a/mens-api/src/main/java/kr/xit/core/biz/batch/task/BatchEndTasklet.java +++ /dev/null @@ -1,57 +0,0 @@ -package kr.xit.core.biz.batch.task; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.MDC; -import org.springframework.batch.core.ExitStatus; -import org.springframework.batch.core.StepContribution; -import org.springframework.batch.core.scope.context.ChunkContext; -import org.springframework.batch.core.step.tasklet.Tasklet; -import org.springframework.batch.repeat.RepeatStatus; - -import kr.xit.core.biz.batch.model.BatchCmmDTO; -import kr.xit.core.biz.batch.service.IBatchCmmService; -import lombok.extern.slf4j.Slf4j; - -/** - *
- * description : 배치 종료시 lock table update
- *               종료하는 배치 인스턴스의 사용여부(use_yn)를 미사용(N)으로 변경
- *
- * packageName : kr.xit.core.biz.batch.task
- * fileName    : BatchEndTasklet
- * author      : limju
- * date        : 2023-05-16
- * ======================================================================
- * 변경일         변경자        변경 내용
- * ----------------------------------------------------------------------
- * 2023-05-16    limju       최초 생성
- *
- * 
- * @see kr.xit.core.aop.TraceLoggerAspect - */ -@Slf4j -public class BatchEndTasklet implements Tasklet { - private final IBatchCmmService batchCmmService; - - public BatchEndTasklet(IBatchCmmService batchCmmService) { - this.batchCmmService = batchCmmService; - } - - @Override - public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { - String jobName = contribution.getStepExecution().getJobExecution().getJobInstance().getJobName(); - contribution.setExitStatus(ExitStatus.COMPLETED); - BatchCmmDTO dto = BatchCmmDTO - .builder() - .instanceId(jobName) - .result(contribution.getExitStatus().getExitCode()) - .useYn("N") - .batchLogId(MDC.get("batch_log_id")) - .traceId(StringUtils.defaultString(MDC.get("request_trace_id"), MDC.get("request_trace_batch_id"))) - .build(); -log.info("@@@@@@@@@@@@@{}", MDC.getCopyOfContextMap()); - batchCmmService.modifyBatchLock(dto); - batchCmmService.modifyBatchLog(dto); - return RepeatStatus.FINISHED; - } -} diff --git a/mens-api/src/main/java/kr/xit/core/biz/batch/task/BatchFailEndTasklet.java b/mens-api/src/main/java/kr/xit/core/biz/batch/task/BatchFailEndTasklet.java deleted file mode 100644 index bc04cde..0000000 --- a/mens-api/src/main/java/kr/xit/core/biz/batch/task/BatchFailEndTasklet.java +++ /dev/null @@ -1,59 +0,0 @@ -package kr.xit.core.biz.batch.task; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.MDC; -import org.springframework.batch.core.ExitStatus; -import org.springframework.batch.core.StepContribution; -import org.springframework.batch.core.scope.context.ChunkContext; -import org.springframework.batch.core.step.tasklet.Tasklet; -import org.springframework.batch.repeat.RepeatStatus; - -import kr.xit.core.biz.batch.model.BatchCmmDTO; -import kr.xit.core.biz.batch.service.IBatchCmmService; -import lombok.extern.slf4j.Slf4j; - -/** - *
- * description : 배치 종료시 lock table update
- *               종료하는 배치 인스턴스의 사용여부(use_yn)를 미사용(N)으로 변경
- *
- * packageName : kr.xit.core.biz.batch.task
- * fileName    : BatchEndTasklet
- * author      : limju
- * date        : 2023-05-16
- * ======================================================================
- * 변경일         변경자        변경 내용
- * ----------------------------------------------------------------------
- * 2023-05-16    limju       최초 생성
- *
- * 
- * @see kr.xit.core.aop.TraceLoggerAspect - */ -@Slf4j -public class BatchFailEndTasklet implements Tasklet { - private final IBatchCmmService batchCmmService; - - public BatchFailEndTasklet(IBatchCmmService batchCmmService) { - this.batchCmmService = batchCmmService; - } - - @Override - public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { - String jobName = contribution.getStepExecution().getJobExecution().getJobInstance().getJobName(); - contribution.setExitStatus(ExitStatus.FAILED); - BatchCmmDTO dto = BatchCmmDTO - .builder() - .instanceId(jobName) - .result(contribution.getExitStatus().getExitCode()) - .useYn("N") - .batchLogId(MDC.get("batch_log_id")) - .traceId(StringUtils.defaultString(MDC.get("request_trace_id"), MDC.get("request_trace_batch_id"))) - .build(); - log.info("@@@@@@@@@@@@@{}", MDC.getCopyOfContextMap()); - - batchCmmService.modifyBatchLock(dto); - batchCmmService.modifyBatchLog(dto); - - return RepeatStatus.FINISHED; - } -} diff --git a/mens-api/src/main/java/kr/xit/core/biz/batch/task/BatchStartTasklet.java b/mens-api/src/main/java/kr/xit/core/biz/batch/task/BatchStartTasklet.java deleted file mode 100644 index b2890ed..0000000 --- a/mens-api/src/main/java/kr/xit/core/biz/batch/task/BatchStartTasklet.java +++ /dev/null @@ -1,75 +0,0 @@ -package kr.xit.core.biz.batch.task; - -import org.slf4j.MDC; -import org.springframework.batch.core.ExitStatus; -import org.springframework.batch.core.StepContribution; -import org.springframework.batch.core.scope.context.ChunkContext; -import org.springframework.batch.core.step.tasklet.Tasklet; -import org.springframework.batch.repeat.RepeatStatus; - -import kr.xit.core.biz.batch.model.BatchCmmDTO; -import kr.xit.core.biz.batch.service.IBatchCmmService; -import kr.xit.core.support.utils.Checks; -import lombok.extern.slf4j.Slf4j; - -/** - *
- * description : 배치 시작시 lock table insert or update
- *               시작하는 배치 인스턴스의 사용여부(use_yn)를 사용(Y)으로 변경(생성)
- *               -> 사용여부가 사용(Y) 이면 실행중 이므로 배치 종료
- *
- * packageName : kr.xit.core.biz.batch.task
- * fileName    : BatchStartTasklet
- * author      : limju
- * date        : 2023-05-16
- * ======================================================================
- * 변경일         변경자        변경 내용
- * ----------------------------------------------------------------------
- * 2023-05-16    limju       최초 생성
- * 2023-08-21    limju       lock이 걸린 경우 release 하도록 변경 : 중복실행 되지 않도록 배치 시간 보장 전제
- * 
- * @see kr.xit.core.aop.TraceLoggerAspect - */ -@Slf4j -public class BatchStartTasklet implements Tasklet { - private final IBatchCmmService batchCmmService; - - public BatchStartTasklet(IBatchCmmService batchCmmService) { - this.batchCmmService = batchCmmService; - } - - @Override - public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { - String jobName = contribution.getStepExecution().getJobExecution().getJobInstance().getJobName(); - BatchCmmDTO dto = batchCmmService.findById(jobName) - .orElseGet(()-> BatchCmmDTO - .builder() - .build()); - - if(Checks.isEmpty(dto.getInstanceId())){ - dto.setInstanceId(jobName); - dto.setResult(null); - dto.setUseYn("Y"); - batchCmmService.addBatchLock(dto); - batchCmmService.addBatchLog(dto); - MDC.put("batch_log_id", dto.getBatchLogId()); - }else{ - if("Y".equals(dto.getUseYn())){ - log.error("======= [{}] 배치 실행(사용) 중으로 종료 =======", jobName); - contribution.setExitStatus(ExitStatus.FAILED); - dto.setResult("배치 실행(사용) 중으로 종료"); - // lock이 걸린 경우 reset : 2023-08-21 - dto.setUseYn("N"); - batchCmmService.modifyBatchLock(dto); - batchCmmService.addBatchLog(dto); - }else{ - dto.setUseYn("Y"); - dto.setResult(null); - batchCmmService.modifyBatchLock(dto); - batchCmmService.addBatchLog(dto); - MDC.put("batch_log_id", dto.getBatchLogId()); - } - } - return RepeatStatus.FINISHED; - } -} diff --git a/mens-api/src/main/java/kr/xit/core/spring/config/support/PrimaryMybatisConfig.java b/mens-api/src/main/java/kr/xit/core/spring/config/support/PrimaryMybatisConfig.java index 4fa2b4e..eb01fcb 100644 --- a/mens-api/src/main/java/kr/xit/core/spring/config/support/PrimaryMybatisConfig.java +++ b/mens-api/src/main/java/kr/xit/core/spring/config/support/PrimaryMybatisConfig.java @@ -38,9 +38,9 @@ import javax.sql.DataSource; @Configuration @MapperScan( basePackages = { - "kr.xit.core.biz.mapper", - "kr.xit.core.biz.batch.mapper", - "kr.xit.biz.ens.mapper", + "kr.xit.core.**.mapper", + "kr.xit.biz.**.mapper", + "kr.xit.ens.**.mapper", }, sqlSessionFactoryRef = Constants.PRIMARY_SQL_SESSION ) diff --git a/mens-api/src/main/java/kr/xit/core/spring/util/ApiSpringUtils.java b/mens-api/src/main/java/kr/xit/core/spring/util/ApiSpringUtils.java index 27e40d7..0216f23 100644 --- a/mens-api/src/main/java/kr/xit/core/spring/util/ApiSpringUtils.java +++ b/mens-api/src/main/java/kr/xit/core/spring/util/ApiSpringUtils.java @@ -4,7 +4,6 @@ import lombok.AccessLevel; import lombok.NoArgsConstructor; import org.springframework.context.ApplicationContext; -import kr.xit.core.biz.batch.service.IBatchCmmService; import kr.xit.core.spring.config.support.ApplicationContextProvider; import kr.xit.core.support.slack.SlackWebhookPush; diff --git a/mens-api/src/main/java/kr/xit/ens/support/cmm/mapper/ICmmEnsMapper.java b/mens-api/src/main/java/kr/xit/ens/support/cmm/mapper/ICmmEnsMapper.java new file mode 100644 index 0000000..7d6ee12 --- /dev/null +++ b/mens-api/src/main/java/kr/xit/ens/support/cmm/mapper/ICmmEnsMapper.java @@ -0,0 +1,27 @@ +package kr.xit.ens.support.cmm.mapper; + +import kr.xit.biz.ens.model.nice.NiceCiDTO.CrtfInfo; +import org.egovframe.rte.psl.dataaccess.mapper.Mapper; + +/** + *
+ * description : 전자고지 공통 mapper
+ *               - cache: CaffeineCache use
+ *
+ * packageName : kr.xit.ens.support.cmm.mapper
+ * fileName    : ICmmEnsMapper
+ * author      : limju
+ * date        : 2023-09-12
+ * ======================================================================
+ * 변경일         변경자        변경 내용
+ * ----------------------------------------------------------------------
+ * 2023-09-12    limju       최초 생성
+ *
+ * 
+ */ +@Mapper +public interface ICmmEnsMapper { + CrtfInfo selectNiceCrtfInfo(final CrtfInfo dto); + + int updateNiceCrtfPublickey(final CrtfInfo dto); +} diff --git a/mens-api/src/main/java/kr/xit/ens/support/cmm/service/CmmEnsCacheService.java b/mens-api/src/main/java/kr/xit/ens/support/cmm/service/CmmEnsCacheService.java new file mode 100644 index 0000000..ad1e021 --- /dev/null +++ b/mens-api/src/main/java/kr/xit/ens/support/cmm/service/CmmEnsCacheService.java @@ -0,0 +1,60 @@ +package kr.xit.ens.support.cmm.service; + +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.stats.CacheStats; +import kr.xit.biz.ens.model.nice.NiceCiDTO.CrtfInfo; +import kr.xit.ens.support.cmm.mapper.ICmmEnsMapper; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.cache.caffeine.CaffeineCache; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Slf4j +@RequiredArgsConstructor +@Service +public class CmmEnsCacheService implements ICmmEnsCacheService { + private final ICmmEnsMapper cmmEnsMapper; + private final CacheManager cacheManager; + + /** + * GET Nice CI 인증 관련 정보 + * @param signguCode + * @param ffnlgCode + * @param clientId + * @return CrtfInfo + */ + @Transactional(readOnly = true) + @Cacheable(cacheNames = "niceCrtfInfo", keyGenerator = "cacheKeyGenerator") + public CrtfInfo getNiceCrtfInfoCache(final String signguCode, final String ffnlgCode, final String clientId) { + return cmmEnsMapper.selectNiceCrtfInfo(CrtfInfo.builder() + .signguCode(signguCode) + .ffnlgCode(ffnlgCode) + .clientId(clientId) + .build()); + } + + @Transactional(readOnly = true) + @CacheEvict(cacheNames = "niceCrtfInfo", keyGenerator = "cacheKeyGenerator") + public void removeNiceCrtfInfoCache(final String signguCode, final String ffnlgCode, final String clientId) { + } + + public void logCache(){ + if(!log.isDebugEnabled()) { + for(String cacheName : cacheManager.getCacheNames()) { + Cache cache = ((CaffeineCache) cacheManager.getCache(cacheName)).getNativeCache(); + + for(Object key : cache.asMap().keySet()) { + Object value = cache.getIfPresent(key); + log.info("key: {} - value: {}", key, value.toString()); + } + + CacheStats stats = cache.stats(); + log.info("cache '{}' - stats : {}", cacheName, stats.toString()); + } + } + } +} diff --git a/mens-api/src/main/java/kr/xit/ens/support/cmm/service/ICmmEnsCacheService.java b/mens-api/src/main/java/kr/xit/ens/support/cmm/service/ICmmEnsCacheService.java new file mode 100644 index 0000000..a8094b5 --- /dev/null +++ b/mens-api/src/main/java/kr/xit/ens/support/cmm/service/ICmmEnsCacheService.java @@ -0,0 +1,28 @@ +package kr.xit.ens.support.cmm.service; + +import kr.xit.biz.ens.model.nice.NiceCiDTO.CrtfInfo; +import org.springframework.cache.annotation.CacheEvict; + +/** + *
+ * description : CaffeineCache 적용
+ *
+ * packageName : kr.xit.ens.support.cmm.service
+ * fileName    : ICmmEnsCacheService
+ * author      : limju
+ * date        : 2023-09-12
+ * ======================================================================
+ * 변경일         변경자        변경 내용
+ * ----------------------------------------------------------------------
+ * 2023-09-12    limju       최초 생성
+ *
+ * 
+ */ +public interface ICmmEnsCacheService { + CrtfInfo getNiceCrtfInfoCache(final String signguCode, final String ffnlgCode, final String clientId); + + + void removeNiceCrtfInfoCache(final String signguCode, final String ffnlgCode, final String clientId); + + void logCache(); +} diff --git a/mens-api/src/main/java/kr/xit/ens/support/nice/service/INiceCiService.java b/mens-api/src/main/java/kr/xit/ens/support/nice/service/INiceCiService.java index 1cccb4a..ccafbe8 100644 --- a/mens-api/src/main/java/kr/xit/ens/support/nice/service/INiceCiService.java +++ b/mens-api/src/main/java/kr/xit/ens/support/nice/service/INiceCiService.java @@ -2,6 +2,9 @@ package kr.xit.ens.support.nice.service; import kr.xit.biz.ens.model.nice.NiceCiDTO.PublickeyRequest; import kr.xit.biz.ens.model.nice.NiceCiDTO.PublickeyResponse; +import kr.xit.biz.ens.model.nice.NiceCiDTO.SymmetrickeyRegRequest; +import kr.xit.biz.ens.model.nice.NiceCiDTO.SymmetrickeyRegResDataBody; +import kr.xit.biz.ens.model.nice.NiceCiDTO.SymmetrickeyRegResponse; import kr.xit.biz.ens.model.nice.NiceCiDTO.TokenRequest; import kr.xit.biz.ens.model.nice.NiceCiDTO.TokenResponse; @@ -37,4 +40,12 @@ public interface INiceCiService { //-------------------------------------------------------------------------------- // 공개키(Publickey) //-------------------------------------------------------------------------------- + + //-------------------------------------------------------------------------------- + // 대칭키 : symmetrickey + //-------------------------------------------------------------------------------- + SymmetrickeyRegResponse requestRegSymmetrickey(SymmetrickeyRegRequest reqDTO); + //-------------------------------------------------------------------------------- + // 대칭키 : symmetrickey + //-------------------------------------------------------------------------------- } diff --git a/mens-api/src/main/java/kr/xit/ens/support/nice/service/NiceCiDummyTestService.java b/mens-api/src/main/java/kr/xit/ens/support/nice/service/NiceCiDummyTestService.java index 4789472..a90e9f4 100644 --- a/mens-api/src/main/java/kr/xit/ens/support/nice/service/NiceCiDummyTestService.java +++ b/mens-api/src/main/java/kr/xit/ens/support/nice/service/NiceCiDummyTestService.java @@ -1,6 +1,8 @@ package kr.xit.ens.support.nice.service; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.Base64; import java.util.Date; import java.util.HashMap; import java.util.List; @@ -24,13 +26,13 @@ import kr.xit.core.exception.BizRuntimeException; import kr.xit.core.spring.annotation.TraceLogging; import kr.xit.core.spring.util.ApiWebClientUtil; import lombok.RequiredArgsConstructor; -import org.apache.logging.log4j.util.Base64Util; import org.egovframe.rte.fdl.cmmn.EgovAbstractServiceImpl; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.stereotype.Service; +import org.springframework.util.Base64Utils; /** *
@@ -51,12 +53,15 @@ import org.springframework.stereotype.Service;
 @RequiredArgsConstructor
 @Service
 public class NiceCiDummyTestService extends EgovAbstractServiceImpl {
-    @Value("${contract.nice.host}")
-    private String HOST;
+    @Value("${contract.nice.signgu-code}")
+    private String SIGNGU_CODE;
+    @Value("${contract.nice.ffnlg-code}")
+    private String FFNLG_CODE;
     @Value("${contract.nice.client-id}")
     private String CLIENT_ID;
-    @Value("${contract.nice.client-secret}")
-    private String CLIENT_SECRET;
+
+    @Value("${contract.nice.host}")
+    private String HOST;
     @Value("${contract.nice.api.generate-token}")
     private String API_GENERATE_TOKEN;
     @Value("${contract.nice.api.revoke-token}")
@@ -88,7 +93,13 @@ public class NiceCiDummyTestService extends EgovAbstractServiceImpl {
         validate(reqDTO);
         Map map = new HashMap<>();
         map.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
-        map.put(HttpHeaders.AUTHORIZATION, String.format("%s %s", AUTH_TYPE_BASIC, Base64Util.encode(String.format("%s:%s", this.CLIENT_ID, this.CLIENT_SECRET))));
+        map.put(HttpHeaders.AUTHORIZATION,
+            String.format("%s %s", AUTH_TYPE_BASIC,
+                Base64Utils.encodeToString(
+                    Base64Utils.encode(String.format("%s:%s", this.CLIENT_ID, "this.CLIENT_SECRET").getBytes(StandardCharsets.UTF_8))
+                )
+            )
+        );
 
         return TokenResponse.builder()
             .dataHeader(ResponseDataHeader.builder()
@@ -170,11 +181,12 @@ public class NiceCiDummyTestService extends EgovAbstractServiceImpl {
             HttpHeaders.AUTHORIZATION,
             String.format("%s %s",
                 type,
-                Base64Util.encode(
-                    String.format("%s:%s:%s",
-                        "accessToken",
-                        (new Date().getTime() / 1000),
-                        this.CLIENT_ID)
+                Base64Utils.encodeToString(
+                    Base64Utils.encode(
+                        String.format("%s:%s:%s",
+                            "accessToken",
+                            (new Date().getTime() / 1000),
+                            this.CLIENT_ID).getBytes(StandardCharsets.UTF_8))
                 )
             )
         );
diff --git a/mens-api/src/main/java/kr/xit/ens/support/nice/service/NiceCiService.java b/mens-api/src/main/java/kr/xit/ens/support/nice/service/NiceCiService.java
index 86d9b4b..87b59c0 100644
--- a/mens-api/src/main/java/kr/xit/ens/support/nice/service/NiceCiService.java
+++ b/mens-api/src/main/java/kr/xit/ens/support/nice/service/NiceCiService.java
@@ -1,42 +1,54 @@
 package kr.xit.ens.support.nice.service;
 
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.core.type.TypeReference;
-import java.nio.charset.Charset;
 import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
+import java.security.InvalidKeyException;
+import java.security.KeyFactory;
+import java.security.NoSuchAlgorithmException;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.X509EncodedKeySpec;
+import java.util.Base64;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
-import java.util.Objects;
+import java.util.Random;
 import java.util.Set;
 import java.util.stream.Collectors;
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.NoSuchPaddingException;
 import javax.validation.ConstraintViolation;
 import javax.validation.Validation;
 import javax.validation.Validator;
-import kr.xit.biz.ens.model.kakao.KkopayDocBulkDTO.BulkSendResponses;
+import kr.xit.biz.ens.model.nice.NiceCiDTO.CrtfInfo;
+import kr.xit.biz.ens.model.nice.NiceCiDTO.PublickeyReqDataBody;
 import kr.xit.biz.ens.model.nice.NiceCiDTO.PublickeyRequest;
+import kr.xit.biz.ens.model.nice.NiceCiDTO.PublickeyResDataBody;
 import kr.xit.biz.ens.model.nice.NiceCiDTO.PublickeyResponse;
-import kr.xit.biz.ens.model.nice.NiceCiDTO.ResponseDataHeader;
+import kr.xit.biz.ens.model.nice.NiceCiDTO.RequestDataHeader;
+import kr.xit.biz.ens.model.nice.NiceCiDTO.SymmetrickeyRegRequest;
+import kr.xit.biz.ens.model.nice.NiceCiDTO.SymmetrickeyRegResponse;
 import kr.xit.biz.ens.model.nice.NiceCiDTO.TokenRequest;
-import kr.xit.biz.ens.model.nice.NiceCiDTO.TokenResDataBody;
 import kr.xit.biz.ens.model.nice.NiceCiDTO.TokenResponse;
 import kr.xit.core.exception.BizRuntimeException;
 import kr.xit.core.spring.annotation.TraceLogging;
 import kr.xit.core.spring.util.ApiWebClientUtil;
+import kr.xit.core.support.utils.DateUtils;
 import kr.xit.core.support.utils.JsonUtils;
+import kr.xit.ens.support.cmm.mapper.ICmmEnsMapper;
+import kr.xit.ens.support.cmm.service.CmmEnsCacheService;
 import lombok.RequiredArgsConstructor;
-import org.apache.logging.log4j.util.Base64Util;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.poi.ss.formula.functions.T;
 import org.egovframe.rte.fdl.cmmn.EgovAbstractServiceImpl;
 import org.springframework.beans.factory.annotation.Value;
+import org.springframework.cache.CacheManager;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.HttpMethod;
 import org.springframework.http.MediaType;
-import org.springframework.http.ResponseEntity;
 import org.springframework.stereotype.Service;
-import org.springframework.util.LinkedMultiValueMap;
-import org.springframework.util.MultiValueMap;
+import org.springframework.util.Base64Utils;
 
 /**
  * 
@@ -54,15 +66,19 @@ import org.springframework.util.MultiValueMap;
  * 
*/ //FIXME : client_id, client_secret, access_token DB 처리후 반영 필요 +@Slf4j @RequiredArgsConstructor @Service public class NiceCiService extends EgovAbstractServiceImpl implements INiceCiService { - @Value("${contract.nice.host}") - private String HOST; + @Value("${contract.nice.signgu-code}") + private String SIGNGU_CODE; + @Value("${contract.nice.ffnlg-code}") + private String FFNLG_CODE; @Value("${contract.nice.client-id}") private String CLIENT_ID; - @Value("${contract.nice.client-secret}") - private String CLIENT_SECRET; + + @Value("${contract.nice.host}") + private String HOST; @Value("${contract.nice.api.generate-token}") private String API_GENERATE_TOKEN; @Value("${contract.nice.api.revoke-token}") @@ -76,9 +92,15 @@ public class NiceCiService extends EgovAbstractServiceImpl implements INiceCiSer private static final String AUTH_TYPE_BASIC = "Basic"; private static final String AUTH_TYPE_BEARER = "bearer"; - private static final Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); + private final ApiWebClientUtil webClient; + private final CmmEnsCacheService cacheService; + private final ICmmEnsMapper cmmEnsMapper; + + private final CacheManager cacheManager; // Bean 주입 + private static int AAA = 0; + //-------------------------------------------------------------------------------- // 기관용 Token @@ -96,7 +118,8 @@ public class NiceCiService extends EgovAbstractServiceImpl implements INiceCiSer Map map = new HashMap<>(); map.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE); - map.put(HttpHeaders.AUTHORIZATION, String.format("%s %s", AUTH_TYPE_BASIC, Base64Util.encode(String.format("%s:%s", this.CLIENT_ID, this.CLIENT_SECRET)))); + map.put(HttpHeaders.AUTHORIZATION, + String.format("%s %s", AUTH_TYPE_BASIC, Base64Utils.encodeToString(Base64Utils.encode(String.format("%s:%s", this.CLIENT_ID, "this.CLIENT_SECRET").getBytes(StandardCharsets.UTF_8))))); return webClient.exchange(HOST + API_GENERATE_TOKEN, HttpMethod.POST, JsonUtils.toJson(reqDTO), TokenResponse.class, map); } @@ -149,6 +172,82 @@ public class NiceCiService extends EgovAbstractServiceImpl implements INiceCiSer // 공개키(Publickey) //-------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------- + // 대칭키 : symmetrickey + //-------------------------------------------------------------------------------- + + /** + *
+     * 0. cache call
+     *  --> 공개키 잔여일 수가 5보다 작으면
+     * 1. 공개키 재발급후 공개키 정보 update
+     * 2. cache 삭제 && cache call
+     * @param reqDTO
+     * @return
+     * 
+ */ + @Override + public SymmetrickeyRegResponse requestRegSymmetrickey(SymmetrickeyRegRequest reqDTO) { + validate(reqDTO); + + + CrtfInfo crtfInfo = getNiceCrtInfo(reqDTO.getDataHeader()); + + + + + return null; + } + + + /** + *
+     * 0. cache call
+     *  --> 공개키 잔여일 수가 5보다 작으면
+     * 1. 공개키 재발급후 공개키 정보 update
+     * 2. cache 삭제 && cache call
+     * @param reqHeader RequestDataHeader
+     * @return
+     * 
+ */ + private CrtfInfo getNiceCrtInfo(RequestDataHeader reqHeader) { + CrtfInfo crtfInfo = cacheService.getNiceCrtfInfoCache(SIGNGU_CODE, FFNLG_CODE, CLIENT_ID); + cacheService.logCache(); + + if(crtfInfo.getRemainingDays() > 5) return crtfInfo; + + //FIXME::공개키 발급요청 call + PublickeyRequest pubReqDTO = PublickeyRequest.builder() + .dataHeader(reqHeader) + .dataBody(PublickeyReqDataBody.builder() + .reqDtim(DateUtils.getTodayAndNowTime("yyyyMMddHHmmss")) + .build()) + .build(); + + PublickeyResponse pubResDTO = requestPublickey(pubReqDTO); + + //FIXME::공개키 정보 갱신 + PublickeyResDataBody dataBody = pubResDTO.getDataBody(); + if(pubResDTO.getDataHeader().getGwRsltCd().equals("1200") + && dataBody.getRspCd().equals("P000") + && dataBody.getResultCd().equals("0000")){ + crtfInfo.setSiteCode(dataBody.getSiteCode()); + crtfInfo.setKeyVersion(dataBody.getKeyVersion()); + crtfInfo.setPublicKey(dataBody.getPublicKey()); + crtfInfo.setValidDtim(dataBody.getValidDtim()); + cmmEnsMapper.updateNiceCrtfPublickey(crtfInfo); + }else{ + //FIXME::예외처리 + } + + cacheService.removeNiceCrtfInfoCache(SIGNGU_CODE, FFNLG_CODE, CLIENT_ID); + return cacheService.getNiceCrtfInfoCache(SIGNGU_CODE, FFNLG_CODE, CLIENT_ID); + } + + //-------------------------------------------------------------------------------- + // 대칭키 : symmetrickey + //-------------------------------------------------------------------------------- + //------------------------------------------------------------------------------- private Map getHeaderMap(final String contentType, final String type){ Map map = new HashMap<>(); @@ -157,11 +256,12 @@ public class NiceCiService extends EgovAbstractServiceImpl implements INiceCiSer HttpHeaders.AUTHORIZATION, String.format("%s %s", type, - Base64Util.encode( - String.format("%s:%s:%s", - "accessToken", - (new Date().getTime() / 1000), - this.CLIENT_ID) + Base64Utils.encodeToString( + Base64Utils.encode( + String.format("%s:%s:%s", + "accessToken", + (new Date().getTime() / 1000), + this.CLIENT_ID).getBytes(StandardCharsets.UTF_8)) ) ) ); @@ -182,4 +282,47 @@ public class NiceCiService extends EgovAbstractServiceImpl implements INiceCiSer .collect(Collectors.toList()).toString()); } } + + + /** + * 암호화 : 공개키를 통한 암호화 + * + * @param strPublicKey + * @param planText + * @return + */ + protected final String encodeString(final String strPublicKey, final String planText) { //throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { + + try { + KeyFactory keyFactory = KeyFactory.getInstance("RSA"); + byte[] cipherEnc = Base64.getDecoder().decode(strPublicKey); + X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(cipherEnc); + java.security.PublicKey publicKey = keyFactory.generatePublic(publicKeySpec); + + Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); + cipher.init(Cipher.ENCRYPT_MODE, publicKey); + byte[] bytePlain = cipher.doFinal(planText.getBytes()); + return Base64Utils.encodeToString(bytePlain); + + } catch (NoSuchAlgorithmException|InvalidKeySpecException|NoSuchPaddingException|InvalidKeyException e){ + throw BizRuntimeException.create(e.getMessage()); + } catch (IllegalBlockSizeException e) { + throw BizRuntimeException.create(e.getMessage()); + } catch (BadPaddingException e) { + throw BizRuntimeException.create(e.getMessage()); + } + } + + protected final String randomAlphaWord(int wordLength) { + Random r = new Random(); + + StringBuilder sb = new StringBuilder(wordLength); + for (int i = 0; i < wordLength; i++) { + char tmp = (char) ('a' + r.nextInt('z' - 'a')); + sb.append(tmp); + + } + return sb.toString(); + + } } diff --git a/mens-api/src/main/java/kr/xit/ens/support/nice/web/NiceCiController.java b/mens-api/src/main/java/kr/xit/ens/support/nice/web/NiceCiController.java index 3deed5e..5b71080 100644 --- a/mens-api/src/main/java/kr/xit/ens/support/nice/web/NiceCiController.java +++ b/mens-api/src/main/java/kr/xit/ens/support/nice/web/NiceCiController.java @@ -1,11 +1,9 @@ package kr.xit.ens.support.nice.web; import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.ExampleObject; import io.swagger.v3.oas.annotations.tags.Tag; -import kr.xit.biz.ens.model.kakao.KkopayDocDTO.ValidTokenRequest; import kr.xit.biz.ens.model.nice.NiceCiDTO.PublickeyRequest; +import kr.xit.biz.ens.model.nice.NiceCiDTO.SymmetrickeyRegRequest; import kr.xit.biz.ens.model.nice.NiceCiDTO.TokenRequest; import kr.xit.core.model.ApiResponseDTO; import kr.xit.ens.support.nice.service.INiceCiService; @@ -14,7 +12,6 @@ import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** @@ -90,8 +87,22 @@ public class NiceCiController { ) { return ApiResponseDTO.success(service.requestPublickey(reqDTO)); } - //-------------------------------------------------------------------------------- // 공개키(Publickey) //-------------------------------------------------------------------------------- + + //-------------------------------------------------------------------------------- + // 대칭키 : symmetrickey + //-------------------------------------------------------------------------------- + @Operation(summary = "대칭키(symmetrickey) 등록 요청", description = "대칭키(symmetrickey) 등록 요청") + @PostMapping(value = "/requestRegSymmetrickey", produces = MediaType.APPLICATION_JSON_VALUE) + public ApiResponseDTO requestRegSymmetrickey( + @RequestBody final SymmetrickeyRegRequest reqDTO + ) { + return ApiResponseDTO.success(service.requestRegSymmetrickey(reqDTO)); + } + + //-------------------------------------------------------------------------------- + // 대칭키 : symmetrickey + //-------------------------------------------------------------------------------- } diff --git a/mens-api/src/main/java/kr/xit/ens/support/nice/web/NiceCiDummyTestController.java b/mens-api/src/main/java/kr/xit/ens/support/nice/web/NiceCiDummyTestController.java index a34ab1a..6041a37 100644 --- a/mens-api/src/main/java/kr/xit/ens/support/nice/web/NiceCiDummyTestController.java +++ b/mens-api/src/main/java/kr/xit/ens/support/nice/web/NiceCiDummyTestController.java @@ -25,6 +25,7 @@ import kr.xit.ens.support.nice.service.NiceCiService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; @@ -59,9 +60,9 @@ public class NiceCiDummyTestController { // 기관용 Token //-------------------------------------------------------------------------------- @Operation(summary = "기관용 토큰 발급 요청", description = "기관용 토큰 발급 요청") - @PostMapping(value = "/generateToken", produces = MediaType.APPLICATION_JSON_VALUE) + @PostMapping(value = "/generateToken", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public ApiResponseDTO generateToken( - @RequestBody final TokenRequest reqDTO + @ModelAttribute final TokenRequest reqDTO ) { return ApiResponseDTO.success(service.generateToken(reqDTO)); } diff --git a/mens-api/src/main/resources/config/application-ens.yml b/mens-api/src/main/resources/config/application-ens.yml index 47ddce3..2431ac0 100644 --- a/mens-api/src/main/resources/config/application-ens.yml +++ b/mens-api/src/main/resources/config/application-ens.yml @@ -27,8 +27,9 @@ contract: nice: #host: http://parking.cheonan.go.kr host: https://svc.niceapi.co.kr:22001 - client-id: "6c3eb1ff-530d-458a-9a6e-e02e3346f679" - client-secret: "960f204ec45bb312b7ad2d6b54b984d9c353b8" + signgu-code: 11000 + ffnlg-code: 11 + client-id: 6c3eb1ff-530d-458a-9a6e-e02e3346f679 api: generate-token: /digital/niceid/oauth/oauth/token revoke-token: /digital/niceid/oauth/oauth/token/revokeById diff --git a/mens-api/src/main/resources/egovframework/mapper/biz/IKkoMyDocMapper.xml b/mens-api/src/main/resources/egovframework/mapper/biz/IKkoMyDocMapper.xml deleted file mode 100644 index e3927b2..0000000 --- a/mens-api/src/main/resources/egovframework/mapper/biz/IKkoMyDocMapper.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - diff --git a/mens-api/src/main/resources/egovframework/mapper/biz/ens-mysql-mapper.xml b/mens-api/src/main/resources/egovframework/mapper/biz/ens-mysql-mapper.xml new file mode 100644 index 0000000..6bd3161 --- /dev/null +++ b/mens-api/src/main/resources/egovframework/mapper/biz/ens-mysql-mapper.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/mens-api/src/main/resources/egovframework/mapper/core/cmm-batch-mysql-mapper.xml b/mens-api/src/main/resources/egovframework/mapper/core/cmm-batch-mysql-mapper.xml deleted file mode 100644 index 79474cf..0000000 --- a/mens-api/src/main/resources/egovframework/mapper/core/cmm-batch-mysql-mapper.xml +++ /dev/null @@ -1,68 +0,0 @@ - - - - - - - - /** cmm-batch-mapper|insertBatchLock-배치락 데이타 생성|julim */ - INSERT INTO tb_cmm_batch_lock ( - instance_id, - regist_dt, - use_yn - ) VALUES ( - #{instanceId}, - NOW(3), - #{useYn} - ) - - - - /** cmm-batch-mapper|updateBatchLock-배치 실행 상태 및 결과 반영|julim */ - UPDATE tb_cmm_batch_lock - SET result = #{result} - , use_yn = #{useYn} - , updt_dt = NOW(3) - WHERE instance_id = #{instanceId} - - - - /** cmm-batch-mapper|insertBatchLog-배치 로그 데이타 생성|julim */ - - SELECT LPAD(NEXTVAL(tb_cmm_batch_log_seq), 20, '0') - - INSERT INTO tb_cmm_batch_log ( - batch_log_id, - instance_id, - trace_id, - result, - message, - regist_dt - ) VALUES ( - #{batchLogId}, - #{instanceId}, - #{traceId}, - #{result}, - #{message}, - NOW(3) - ) - - - - /** cmm-batch-mapper|updateBatchLog-배치 결과 반영|julim */ - UPDATE tb_cmm_batch_log - SET trace_id = IFNULL(#{traceId}, trace_id) - , result = IFNULL(#{result}, result) - , message = IFNULL(SUBSTRING(#{message}, 1, 100), message) - , updt_dt = NOW(3) - WHERE batch_log_id = #{batchLogId} - - diff --git a/mens-batch/src/main/java/kr/xit/core/spring/config/support/PrimaryMybatisConfig.java b/mens-batch/src/main/java/kr/xit/core/spring/config/support/PrimaryMybatisConfig.java index 0727f2a..d2b6133 100644 --- a/mens-batch/src/main/java/kr/xit/core/spring/config/support/PrimaryMybatisConfig.java +++ b/mens-batch/src/main/java/kr/xit/core/spring/config/support/PrimaryMybatisConfig.java @@ -38,10 +38,8 @@ import javax.sql.DataSource; @Configuration @MapperScan( basePackages = { - "kr.xit.core.biz.mapper", - "kr.xit.core.biz.batch.mapper", - "kr.xit.biz.ens.mapper", - "kr.xit.biz.pni.mapper" + "kr.xit.core.**.mapper", + "kr.xit.biz.**.mapper", }, sqlSessionFactoryRef = Constants.PRIMARY_SQL_SESSION ) diff --git a/mens-api/src/main/java/kr/xit/core/biz/model/AuditFields.java b/mens-core/src/main/java/kr/xit/biz/common/AuditFields.java similarity index 92% rename from mens-api/src/main/java/kr/xit/core/biz/model/AuditFields.java rename to mens-core/src/main/java/kr/xit/biz/common/AuditFields.java index 047a551..caea727 100644 --- a/mens-api/src/main/java/kr/xit/core/biz/model/AuditFields.java +++ b/mens-core/src/main/java/kr/xit/biz/common/AuditFields.java @@ -1,17 +1,12 @@ -package kr.xit.core.biz.model; - -import java.io.Serializable; -import java.time.LocalDateTime; +package kr.xit.biz.common; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; - +import java.time.LocalDateTime; import lombok.AllArgsConstructor; -import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; -import lombok.ToString; import lombok.experimental.SuperBuilder; /** diff --git a/mens-core/src/main/java/kr/xit/biz/ens/model/nice/NiceCiDTO.java b/mens-core/src/main/java/kr/xit/biz/ens/model/nice/NiceCiDTO.java index 389f1e5..b207433 100644 --- a/mens-core/src/main/java/kr/xit/biz/ens/model/nice/NiceCiDTO.java +++ b/mens-core/src/main/java/kr/xit/biz/ens/model/nice/NiceCiDTO.java @@ -8,12 +8,17 @@ import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.annotation.JsonNaming; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema.RequiredMode; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; import javax.validation.Valid; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; +import kr.xit.biz.common.AuditFields; import kr.xit.core.model.IApiResponse; +import kr.xit.core.support.utils.JsonUtils; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Builder.Default; @@ -197,10 +202,10 @@ public class NiceCiDTO { //-------------------------------------------------------------------------------- /** *
-     * 공개키 요청
+     * 공개키(publickey) 요청
      * 
*/ - @Schema(name = "PublickeyRequest", description = "공개키 요청 파라메터 DTO") + @Schema(name = "PublickeyRequest", description = "공개키(publickey) 요청 파라메터 DTO") @Data @NoArgsConstructor @AllArgsConstructor @@ -218,10 +223,10 @@ public class NiceCiDTO { /** *
-     * 공개키 발급 요청 응답
+     * 공개키(publickey) 발급 요청 응답
      * 
*/ - @Schema(name = "PublickeyResponse", description = "공개키 발급 요청 결과 DTO") + @Schema(name = "PublickeyResponse", description = "공개키(publickey) 발급 요청 결과 DTO") @Data @NoArgsConstructor @AllArgsConstructor @@ -239,11 +244,11 @@ public class NiceCiDTO { /** *
-     * 공개키 요청 dataBody DTO
+     * 공개키(publickey) 요청 dataBody DTO
      * Json data : SNAKE_CASE (req_dtim <-> reqDtim)
      * 
*/ - @Schema(name = "PublickeyReqDataBody", description = "공개키 요청 dataBody DTO") + @Schema(name = "PublickeyReqDataBody", description = "공개키(publickey) 요청 dataBody DTO") @Data @NoArgsConstructor @AllArgsConstructor @@ -255,17 +260,17 @@ public class NiceCiDTO { * 공개키 요청일시 (YYYYMMDDHH24MISS) */ @Schema(requiredMode = RequiredMode.REQUIRED, title = "공개키 요청일시", example = "2023090612122259") - @Size(min = 16, max = 16, message = "요청일시(req_dtim)는 필수 입니다(16자리)") + @Size(min = 14, max = 14, message = "요청일시(req_dtim)는 필수 입니다(14자리)") private String reqDtim; } /** *
-     * 공개키 요청 응답 dataBody DTO
+     * 공개키(publickey) 요청 응답 dataBody DTO
      * Json data : SNAKE_CASE (rsp_cd <-> rspCd)
      * 
*/ - @Schema(name = "PublickeyResDataBody", description = "공개키 요청 응답 dataBody DTO") + @Schema(name = "PublickeyResDataBody", description = "공개키(publickey) 요청 응답 dataBody DTO") @Data @NoArgsConstructor @AllArgsConstructor @@ -337,11 +342,154 @@ public class NiceCiDTO { //-------------------------------------------------------------------------------- //-------------------------------------------------------------------------------- - // 대칭키 : publickey + // 대칭키 : symmetrickey //-------------------------------------------------------------------------------- + /** + *
+     * 대칭키(symmetrickey) 등록 요청
+     * 
+ */ + @Schema(name = "SymmetrickeyRegRequest", description = "대칭키(symmetrickey) 등록 요청 파라메터 DTO") + @Data + @NoArgsConstructor + @AllArgsConstructor + @SuperBuilder + @JsonInclude(JsonInclude.Include.NON_EMPTY) + public static class SymmetrickeyRegRequest { + @Schema(requiredMode = RequiredMode.REQUIRED) + @Valid + private RequestDataHeader dataHeader; + + @Schema(requiredMode = RequiredMode.REQUIRED) + @Valid + private SymmetrickeyRegReqDataBody dataBody; + } + + /** + *
+     * 대칭키(symmetrickey) 등록 요청 응답
+     * 
+ */ + @Schema(name = "SymmetrickeyRegResponse", description = "대칭키(symmetrickey) 등록 요청 결과 DTO") + @Data + @NoArgsConstructor + @AllArgsConstructor + @SuperBuilder + @JsonInclude(JsonInclude.Include.NON_EMPTY) + public static class SymmetrickeyRegResponse implements IApiResponse { + @Schema(requiredMode = RequiredMode.REQUIRED) + @Valid + private ResponseDataHeader dataHeader; + + @Schema(requiredMode = RequiredMode.REQUIRED) + @Valid + private SymmetrickeyRegResDataBody dataBody; + } + + /** + *
+     * 대칭키(symmetrickey) 등록 요청 dataBody DTO
+     * Json data : SNAKE_CASE (req_dtim <-> reqDtim)
+     * 
+ */ + @Schema(name = "SymmetrickeyRegReqDataBody", description = "대칭키(symmetrickey) 등록 요청 dataBody DTO") + @Data + @NoArgsConstructor + @AllArgsConstructor + @SuperBuilder + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class) + public static class SymmetrickeyRegReqDataBody { + /** + *
+ * 공개키버전 + * + */ + @Schema(requiredMode = RequiredMode.REQUIRED, title = "공개키버전", example = "20210121ca8c1612-2c2d-IPaa-aad1-xxxxxxxxxxxx") + @Size(min = 1, max = 50, message = "공개키버전은 필수 입니다") + private String pubkeyVersion; + + /** + *
+         * json암호화값(회원사에서 생성한 대칭키를 공개키로 암호화한 값)
+         * 암호화알고리즘 : RSA/ECB/PKCS1Padding, X509EncodedKeySpec 사용, Base64 Encoding
+         * site_code - 16 : 공개키요청시 수신한 사이트 코드
+         * request_no - 30 : 이용기관에서 임의 생성한 값
+         * key - 32 : 회원사에서 사용할 암호화 KEY 세팅
+         *            32byte AES256 bits, 16byte AES128 bits
+         *            NICE에 KEY등록 후 최대 6개월 내 갱신 필요
+         * iv - 16 : Inital Vector값
+         * hmac_key - 32 : 화원사에서 사용할 HMAC KEY
+         * 
+ */ + @Schema(requiredMode = RequiredMode.REQUIRED, title = "json암호화값(회원사에서 생성한 대칭키를 공개키로 암호화한 값)", example = "SDFWASDFASDFSDFASDFASDFASD=") + @Size(min = 1, max = 512, message = "대칭키(암호화)는 필수 입니다") + private String symkeyRegInfo; + } + + /** + *
+     * 대칭키(symmetrickey) 등록 요청 응답 dataBody DTO
+     * Json data : SNAKE_CASE (rsp_cd <-> rspCd)
+     * 
+ */ + @Schema(name = "SymmetrickeyRegResDataBody", description = "대칭키(symmetrickey) 등록 요청 응답 dataBody DTO") + @Data + @NoArgsConstructor + @AllArgsConstructor + @SuperBuilder + @JsonInclude(Include.NON_EMPTY) + @JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class) + public static class SymmetrickeyRegResDataBody { + /** + * dataBody 정상처리여부 (P000 성공, 이외 모두 오류) : 8자리 + */ + @Schema(requiredMode = RequiredMode.REQUIRED, title = "정상처리 여부", example = "P000") + private String rspCd; + + /** + *
+         * rsp_cd가 "EAPI"로 시작될 경우 오류 메시지 세팅
+         * 최대 200
+         * 
+ */ + @Schema(requiredMode = RequiredMode.REQUIRED, title = "상세 메세지", example = " ") + private String rspMsg; + /** + *
+         * rsp_cd가 P000일 때 상세결과코드 : 4자리
+         * - 0000: 대칭키 발급
+         * - 0001: 공개키 기간 만료
+         * - 0002: 공개키를 찾을 수 없음
+         * - 0003: 공개키를 발급한 회원사 아님
+         * - 0004: 복호화 오류
+         * - 0005: 필수입력값 오류 (key_version, key_info 필수값 확인)
+         * - 0006: 대칭키 등록 가능 회원사 아님
+         * - 0007: key 중복 오류 (현재 및 직전에 사용한 Key 사용 불가)
+         * - 0008: 요청사이트코드와 공개키발급 사이트코드 다름
+         * - 0099: 기타오류
+         * 
+ */ + @Schema(requiredMode = RequiredMode.AUTO, title = "상세 결과코드", example = "0000") + private String resultCd; + + /** + *
+         * JSON값
+         * - 회원사에 생성되어있는 대칭키 버전별 유효기간
+         * - result_cd 0000, 0007일 경우 나감
+         * cur_symkey_version - 50 : 현재 등록요청한 대칭키 버전
+         * cur_valid_dtim - 14 : 현재 등록된 대칭키 만료일시 (YYYYMMDDHH24MISS)
+         * bef_symkey_version - 50 : 이전 등록된 대칭키 버전
+         * bef_valid_dtim - 14 : 이전 등록된 대칭키 만료일시 (YYYYMMDDHH24MISS)
+         * 
+ */ + @Schema(requiredMode = RequiredMode.AUTO, title = "사이트 코드", example = " ") + private String symkeyStatInfo; + } //-------------------------------------------------------------------------------- - // 공개키 : publickey + // 대칭키 : symmetrickey //-------------------------------------------------------------------------------- @@ -433,4 +581,93 @@ public class NiceCiDTO { + public String genSymkeyRegInfo() { + /* + final String requestNo = createRequestNo(); + final String key = this.createKey(); + final String iv = this.createIv(); + final String hmacKey = this.createHmacKey(); +*/ + Map m = new HashMap<>(); + /*m.put("site_code", siteCode); + m.put("request_no", requestNo); + m.put("key", key); + m.put("iv", iv); + m.put("hmac_key", hmacKey);*/ + + final String jsonStr = JsonUtils.toJson(m); + //final String jsonStr = this.createMessage(pubkeyVersion, encSymkeyRegInfo(jsonStr, publicKey)); + + return JsonUtils.toJson(m); + } + + /** + * Nice 계정 인증 정보 DTO + */ + @Data + @NoArgsConstructor + @AllArgsConstructor + @SuperBuilder + public static class CrtfInfo extends AuditFields implements Serializable { + private static final long serialVersionUID = 1L; + + /** + * 시군구 코드 + */ + private String signguCode; + /** + * 과태료 코드 + */ + private String ffnlgCode; + /** + * 전자문서중계구분코드 + */ + private String clientId; + /** + * App Security code + */ + private String clientSecret; + /** + * 상품코드 + */ + private String productId; + /** + * access token + */ + private String accessToken; + /** + * access token 만료일시(초) + */ + private long expiresIn; + /** + * token type-bearer + */ + private String tokenType; + /** + * token scope-default + */ + private String scope; + /** + * 공개키 site code + */ + private String siteCode; + /** + * 공개키 버전 + */ + private String keyVersion; + /** + * 공개키 + */ + private String publicKey; + /** + * 공개키 만료일시 + */ + private String validDtim; + + + /** + * 공개키 잔여일수 + */ + private int remainingDays; + } } diff --git a/mens-core/src/main/java/kr/xit/core/support/utils/SecureUtils.java b/mens-core/src/main/java/kr/xit/core/support/utils/SecureUtils.java index b2f7416..8eb2801 100644 --- a/mens-core/src/main/java/kr/xit/core/support/utils/SecureUtils.java +++ b/mens-core/src/main/java/kr/xit/core/support/utils/SecureUtils.java @@ -1,9 +1,20 @@ package kr.xit.core.support.utils; import java.io.IOException; +import java.security.InvalidKeyException; +import java.security.KeyFactory; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.X509EncodedKeySpec; +import java.util.Base64; +import java.util.Random; +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; import kr.xit.core.exception.BizRuntimeException; +import org.springframework.util.Base64Utils; /** *
@@ -49,4 +60,5 @@ public class SecureUtils {
         }
         return sbuf.toString();
     }
+
 }