refactor: 미사용 클래스 제거

main
Jonguk. Lim 2 months ago
parent d011b2eb91
commit df55794439

@ -1,274 +0,0 @@
package cokr.xit.ens.core.aop;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonRootName;
import com.google.gson.GsonBuilder;
import cokr.xit.ens.core.exception.BizRuntimeException;
import cokr.xit.ens.core.exception.code.ErrorCode;
import cokr.xit.ens.core.utils.Checks;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* <pre>
* description : Api
* TODO :: json @JsonIgnore
* packageName : kr.xit.core.model
* fileName : ApiResponseDTO
* author : julim
* date : 2023-04-28
* ======================================================================
*
* ----------------------------------------------------------------------
* 2023-04-28 julim
*
* </pre>
*/
@Schema(name = "ApiResponseDTO", description = "Restful API 결과")
@Data
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor
@Builder
@JsonRootName("result")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ApiResponseDTO<T> implements IApiResponse {
private static final String FAIL_STATUS = "fail";
private static final String ERROR_STATUS = "error";
@Schema(example = "true", description = "에러인 경우 false", requiredMode = Schema.RequiredMode.REQUIRED)
private boolean success;
@Schema(example = " ", description = "HttpStatus.OK", requiredMode = Schema.RequiredMode.REQUIRED)
private String code;
@Schema(description = "결과 데이타, 오류시 null", example = " ")
private T data;
@Schema(description = "오류 발생시 오류 메세지", example = " ", requiredMode = Schema.RequiredMode.AUTO)
@Setter
private String message;
@JsonIgnore
@Schema(example = " ", description = "HttpStatus.OK", requiredMode = Schema.RequiredMode.AUTO)
private HttpStatus httpStatus;
@Schema(description = "API 실행 결과 데이타 수")
private int count;
/**
* ApiResponseDTO<T> return
*
* @param future CompletableFuture<T>
* @return ApiResponseDTO<T>
*/
//@SuppressWarnings("unchecked")
@SuppressWarnings("rawtypes")
public static <T> ApiResponseDTO of(final CompletableFuture<T> future) {
try {
if(future.get() instanceof ApiResponseDTO<?>) return (ApiResponseDTO)future.get();
return new ApiResponseDTO<>(true, future.get(), String.valueOf(HttpStatus.OK.value()),
HttpStatus.OK.name(), HttpStatus.OK);
} catch (InterruptedException ie){
// thread pool에 에러 상태 전송
Thread.currentThread().interrupt();
throw BizRuntimeException.create(ie);
} catch (ExecutionException ee) {
throw BizRuntimeException.create(ee);
}
}
/**
* ApiResponseDTO<T> return
* @return ApiResponseDTO<T>
*/
public static <T> ApiResponseDTO<T> success() {
return new ApiResponseDTO<>(true, null, String.valueOf(HttpStatus.OK.value()), HttpStatus.OK.name(), HttpStatus.OK);
}
/**
* ApiResponseDTO<T> return
* @param data T
* @return ApiResponseDTO<T>
*/
public static <T> ApiResponseDTO<T> success(T data) {
return new ApiResponseDTO<>(true, data, String.valueOf(HttpStatus.OK.value()), HttpStatus.OK.name(), HttpStatus.OK);
}
/**
* ApiResponseDTO<T> return
* @param httpStatus HttpStatus
* @return ApiResponseDTO<T>
*/
public static <T> ApiResponseDTO<T> success(final HttpStatus httpStatus) {
return new ApiResponseDTO<>(true, null, String.valueOf(httpStatus.value()), httpStatus.name(), httpStatus);
}
/**
* ApiResponseDTO<T> return
* @param data T
* @param httpStatus HttpStatus
* @return ApiResponseDTO<T>
*/
public static <T> ApiResponseDTO<T> success(final T data, final HttpStatus httpStatus) {
return new ApiResponseDTO<>(true, data, String.valueOf(httpStatus.value()), httpStatus.name(), httpStatus);
}
/**
* ApiResponseDTO<T> return
* @param data T
* @param message String
* @return ApiResponseDTO<T>
*/
public static <T> ApiResponseDTO<T> success(final T data, final String message) {
return new ApiResponseDTO<>(true, data, String.valueOf(HttpStatus.OK.value()), message, HttpStatus.OK);
}
/**
* return - body empty
* @return ApiResponseDTO
*/
public static <T> ApiResponseDTO<T> empty() {
return new ApiResponseDTO<>(true, null, String.valueOf(HttpStatus.NO_CONTENT.value()), HttpStatus.NO_CONTENT.name(), HttpStatus.OK);
}
/**
* Error ApiResponseDTO return
* Hibernate Validator API
* @param bindingResult BindingResult
* @return ApiResponseDTO
*/
public static <T> ApiResponseDTO<T> error(final BindingResult bindingResult) {
Map<String, String> errors = new HashMap<>();
List<ObjectError> allErrors = bindingResult.getAllErrors();
for (ObjectError error : allErrors) {
if (error instanceof FieldError) {
errors.put(((FieldError) error).getField(), error.getDefaultMessage());
} else {
errors.put( error.getObjectName(), error.getDefaultMessage());
}
}
return new ApiResponseDTO<>(false, null, FAIL_STATUS, errors.toString(), null);
}
/**
* Error ApiResponseDTO return
* @param message
* @return ApiResponseDTO
*/
public static <T> ApiResponseDTO<T> error(final String message) {
return new ApiResponseDTO<>(false, null, ERROR_STATUS, message, null);
}
/**
* Error ApiResponseDTO return
* @param errorCode ErrorCode
* @return ApiResponseDTO
*/
public static <T> ApiResponseDTO<T> error(final ErrorCode errorCode) {
return new ApiResponseDTO<>(false, null, errorCode.name(), errorCode.getMessage(), errorCode.getHttpStatus());
}
/**
* Error ApiResponseDTO return
* @param e BizRuntimeException
* @return ApiResponseDTO
*/
public static <T> ApiResponseDTO<T> error(final BizRuntimeException e) {
if (Checks.isNotEmpty(e.getErrorCode())) {
return ApiResponseDTO.error(e.getErrorCode());
}
return new ApiResponseDTO<>(
false,
null,
org.apache.commons.lang3.StringUtils.defaultString(e.getCode(), org.apache.commons.lang3.StringUtils.EMPTY),
org.apache.commons.lang3.StringUtils.defaultString(e.getMessage(), org.apache.commons.lang3.StringUtils.EMPTY),
e.getHttpStatus());
}
/**
* Error ApiResponseDTO return
* @param code
* @param message
* @return ApiResponseDTO
*/
public static <T> ApiResponseDTO<T> error(final String code, final String message) {
return new ApiResponseDTO<>(false, null, code, message, null);
}
/**
* Error ApiResponseDTO return
* @param code
* @param message
* @param httpStatus HttpStatus
* @return ApiResponseDTO
*/
public static <T> ApiResponseDTO<T> error(final String code, final String message, HttpStatus httpStatus) {
return new ApiResponseDTO<>(false, null, code, message, httpStatus);
}
/**
*
* @param success true|false
* @param data data
* @param code
* @param message ( )
* @param httpStatus HttpStatus
*/
private ApiResponseDTO(final boolean success, final T data, final String code, final String message, final HttpStatus httpStatus) {
this.success = success;
this.data = data;
this.code = code;
this.message = message;
this.httpStatus = httpStatus;
if(data == null){
this.count = 0;
}else {
if (Collection.class.isAssignableFrom(data.getClass())) {
this.count = (((Collection<?>) data).size());
} else {
this.count = 1;
}
}
if(httpStatus == null){
if(!success) this.httpStatus = HttpStatus.BAD_REQUEST;
else this.httpStatus = HttpStatus.OK;
}
}
@Override
public String toString() {
// value가 null값인 경우도 생성
GsonBuilder builder = new GsonBuilder().serializeNulls();
builder.disableHtmlEscaping();
return builder.setPrettyPrinting().create().toJson(this);
}
}

@ -1,19 +0,0 @@
package cokr.xit.ens.core.aop;
/**
* <pre>
* description :
*
* packageName : kr.xit.core.model
* fileName : IApiResponse
* author : limju
* date : 2023-05-31
* ======================================================================
*
* ----------------------------------------------------------------------
* 2023-05-31 limju
*
* </pre>
*/
public interface IApiResponse {
}

@ -1,245 +0,0 @@
package cokr.xit.ens.core.config.support;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.http.codec.json.Jackson2JsonDecoder;
import org.springframework.http.codec.json.Jackson2JsonEncoder;
import org.springframework.web.reactive.function.client.ClientRequest;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import org.springframework.web.reactive.function.client.ExchangeStrategies;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.util.DefaultUriBuilderFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import cokr.xit.ens.core.exception.BizRuntimeException;
import cokr.xit.ens.core.exception.ClientErrorException;
import cokr.xit.ens.core.exception.ServerErrorException;
import io.netty.channel.ChannelOption;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;
import reactor.netty.http.client.HttpClient;
import reactor.netty.resources.ConnectionProvider;
import reactor.netty.transport.logging.AdvancedByteBufFormat;
/**
* <pre>
* description : WebClient configuration
* Spring WebFlux HTTP Client Config
* logging : - ExchangeFilterFunction (requestFilter, responseFilter)
* - logging.level.reactor.netty.http.client: DEBUG|ERROR
*
* packageName : kr.xit.core.spring.config.support
* fileName : WebClientConfig
* author : julim
* date : 2023-09-06
* ======================================================================
*
* ----------------------------------------------------------------------
* 2023-09-06 julim
*
* </pre>
*/
@Slf4j
@RequiredArgsConstructor
@Configuration
public class WebClientConfig {
@Value("${app.contract.connection.timeout:5000}")
private int connectTimeout;
@Value("${app.contract.connection.readTimeout:5000}")
private int readTimeout;
private final ObjectMapper objectMapper;
DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory();
/**
* setEncodingMode : GET URI 릿
* @return
*/
@Bean
public WebClient webClient() {
factory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.VALUES_ONLY);
return WebClient.builder()
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.uriBuilderFactory(factory)
.clientConnector(new ReactorClientHttpConnector(defaultHttpClient()))
.codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(2 * 1024 * 1024))
.exchangeStrategies(defaultExchangeStrategies())
.filters(exchangeFilterFunctions -> {
//exchangeFilterFunctions.add(requestFilter());
exchangeFilterFunctions.add(responseFilter());
})
.build();
}
/**
* <pre>
* Http client
* - / debugging wiretap - AdvancedByteBufFormat.TEXTUAL
* @return HttpClient
* </pre>
*/
@Bean
public HttpClient defaultHttpClient() {
try {
// SSL check bypass
SslContext sslContext = SslContextBuilder
.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.build();
return HttpClient.create(connectionProvider())
.secure(t -> t.sslContext(sslContext))
.wiretap(this.getClass().getCanonicalName(), LogLevel.DEBUG,
AdvancedByteBufFormat.TEXTUAL)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout)
.responseTimeout(Duration.ofMillis(this.connectTimeout))
.doOnConnected(conn ->
conn.addHandlerLast(new ReadTimeoutHandler(readTimeout, TimeUnit.MILLISECONDS))
.addHandlerLast(
new WriteTimeoutHandler(readTimeout, TimeUnit.MILLISECONDS)));
}catch(SSLException se){
throw BizRuntimeException.create(se.getMessage());
}
}
/**
* maxConnections : connection pool
* pendingAcquireTimeout :
* pendingAcquireMaxCount : (-1: no limit)
* maxIdleTime : idle
* @return ConnectionProvider
*/
@Bean
public ConnectionProvider connectionProvider() {
return ConnectionProvider.builder("http-pool")
.maxConnections(100)
.pendingAcquireTimeout(Duration.ofMillis(0))
.pendingAcquireMaxCount(-1)
.maxIdleTime(Duration.ofMillis(2000L))
.build();
}
/**
* <pre>
* 1. 256KB HTTP DataBufferLimitException
* 2. messageWriters logging(setEnableLoggingRequestDetails(true)
* -> org.springframework.web.reactive.function.client.ExchangeFunctions: DEBUG
* -> defaultHttpClient() wiretap
* </pre>
* @return ExchangeStrategies
*/
@Bean
public ExchangeStrategies defaultExchangeStrategies() {
// 256KB 보다 큰 HTTP 메시지를 처리 시도 → DataBufferLimitException 에러 발생 방어
return ExchangeStrategies.builder()
.codecs(config -> {
config.defaultCodecs().maxInMemorySize(2 * 1024 * 1024);
config.defaultCodecs().jackson2JsonEncoder(new Jackson2JsonEncoder(objectMapper, MediaType.APPLICATION_JSON));
config.defaultCodecs().jackson2JsonDecoder(new Jackson2JsonDecoder(objectMapper, MediaType.APPLICATION_JSON));
})
.build();
// es.messageWriters()
// .stream()
// .filter(LoggingCodecSupport.class::isInstance)
// .forEach(writer -> ((LoggingCodecSupport)writer).setEnableLoggingRequestDetails(true));
}
private ExchangeFilterFunction requestFilter() {
return ExchangeFilterFunction.ofRequestProcessor(cr -> {
if (log.isDebugEnabled()) {
StringBuilder sb = new StringBuilder("\n>>>>>>>>>> WebClient Http Request <<<<<<<<<<<<<\n");
sb.append(logMethodAndUrl(cr));
sb.append(logHeaders(cr));
sb.append("-------------------------------------------------------");
log.debug(sb.toString());
}
return Mono.just(cr);
});
}
/**
* reponse logging && error Handling
* @return ExchangeFilterFunction
*/
private ExchangeFilterFunction responseFilter() {
return ExchangeFilterFunction.ofResponseProcessor(cr -> {
HttpStatus status = cr.statusCode();
if(cr.statusCode().is4xxClientError()) {
return cr.bodyToMono(String.class)
.flatMap(errorBody -> Mono.error(new ClientErrorException(status, errorBody)));
} else if(cr.statusCode().is5xxServerError()) {
return cr.bodyToMono(String.class)
.flatMap(errorBody -> Mono.error(new ServerErrorException(status, errorBody)));
}
// if(log.isDebugEnabled()) {
// StringBuilder sb = new StringBuilder(
// "\n>>>>>>>>>> WebClient Http Response <<<<<<<<<<<<<\n");
// sb.append(logStatus(cr));
// sb.append(logHeaders(cr));
// sb.append("-------------------------------------------------------");
// log.debug(sb.toString());
// }
return Mono.just(cr);
});
}
private static String logStatus(ClientResponse response) {
HttpStatus status = response.statusCode();
return String.format("Returned staus code %s (%s)", status.value(), status.getReasonPhrase());
}
private static String logHeaders(ClientRequest request) {
StringBuilder sb = new StringBuilder();
request.headers()
.forEach((name, values) ->
values.forEach(value -> sb.append(name).append(": ").append(value).append("\n"))
);
return sb.toString();
}
private static String logHeaders(ClientResponse response) {
StringBuilder sb = new StringBuilder();
response.headers()
.asHttpHeaders()
.forEach((name, values) ->
values.forEach(value -> sb.append(name).append(": ").append(value).append("\n"))
);
return sb.toString();
}
private static String logMethodAndUrl(ClientRequest request) {
StringBuilder sb = new StringBuilder();
sb.append(request.method().name());
sb.append(" to ");
sb.append(request.url());
return sb.append("\n").toString();
}
}

@ -1,33 +0,0 @@
package cokr.xit.ens.core.exception;
import org.springframework.http.HttpStatus;
import cokr.xit.ens.core.utils.ApiWebClientUtil;
import lombok.Getter;
/**
* <pre>
* description : WebClient 4xx :
*
* packageName : kr.xit.core.exception
* fileName : ClientErrorException
* author : limju
* date : 2023-05-25
* ======================================================================
*
* ----------------------------------------------------------------------
* 2023-05-25 limju
*
* </pre>
* @see ApiWebClientUtil
*/
@Getter
public class ClientErrorException extends RuntimeException {
private final HttpStatus status;
private final String body;
public ClientErrorException(HttpStatus status, String body) {
this.status = status;
this.body = body;
}
}

@ -1,99 +0,0 @@
package cokr.xit.ens.core.exception;
import java.util.concurrent.ExecutionException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.client.WebClientRequestException;
import cokr.xit.ens.core.aop.ApiResponseDTO;
import cokr.xit.ens.core.utils.Checks;
import io.netty.channel.ConnectTimeoutException;
import io.netty.handler.timeout.ReadTimeoutException;
/**
* <pre>
* description :
*
* packageName : kr.xit.core.exception
* fileName : ErrorParse
* author : limju
* date : 2023-06-01
* ======================================================================
*
* ----------------------------------------------------------------------
* 2023-06-01 limju
*
* </pre>
*/
public class ErrorParse {
@SuppressWarnings("rawtypes")
public static ApiResponseDTO extractError(final Throwable e){
String errCode = String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value());
String message = Checks.isNotNull(e) ? e.getLocalizedMessage() : StringUtils.EMPTY;
HttpStatus httpStatus = null;
if(e instanceof BizRuntimeException) {
BizRuntimeException be = (BizRuntimeException) e;
return ApiResponseDTO.error(be.getCode(), be.getMessage(), HttpStatus.BAD_REQUEST);
}
if(e instanceof ClientErrorException) {
ClientErrorException ce = (ClientErrorException) e;
return ApiResponseDTO.error(String.valueOf(ce.getStatus()), ce.getBody(), ce.getStatus());
}
if(e instanceof ServerErrorException) {
ServerErrorException ce = (ServerErrorException) e;
return ApiResponseDTO.error(String.valueOf(ce.getStatus()), ce.getBody(), ce.getStatus());
}
// Async(React) Exception 처리
if(e instanceof WebClientRequestException) {
if (e.getCause() instanceof ConnectTimeoutException || e.getCause() instanceof ReadTimeoutException) {
return getTimeoutException();
}
}
if(e instanceof ExecutionException) {
if (e.getCause() instanceof WebClientRequestException) {
message = e.getCause().getMessage();
// Timeout 에러
if (e.getCause().getCause() instanceof ReadTimeoutException || e.getCause().getCause() instanceof ConnectTimeoutException) {
return getTimeoutException();
}
}
}
if(e instanceof ReadTimeoutException){
return getTimeoutException();
}
// Async(React) Exception 처리
if(e.getCause() instanceof WebClientRequestException){
// Timeout 에러
if(e.getCause().getCause() instanceof ReadTimeoutException){
return getTimeoutException();
}
}
if(Checks.isNotEmpty(e.getCause())) {
message = e.getCause().getMessage();
}
return ApiResponseDTO.error(errCode, message, httpStatus);
}
@SuppressWarnings("rawtypes")
private static ApiResponseDTO getTimeoutException(){
return ApiResponseDTO.error(
String.valueOf(HttpStatus.REQUEST_TIMEOUT.value()),
HttpStatus.REQUEST_TIMEOUT.getReasonPhrase(),
HttpStatus.REQUEST_TIMEOUT);
}
}

@ -1,33 +0,0 @@
package cokr.xit.ens.core.exception;
import org.springframework.http.HttpStatus;
import cokr.xit.ens.core.utils.ApiWebClientUtil;
import lombok.Getter;
/**
* <pre>
* description : WebClient 5xx :
*
* packageName : kr.xit.core.exception
* fileName : ServerErrorException
* author : limju
* date : 2023-05-25
* ======================================================================
*
* ----------------------------------------------------------------------
* 2023-05-25 limju
*
* </pre>
* @see ApiWebClientUtil
*/
@Getter
public class ServerErrorException extends RuntimeException {
private final HttpStatus status;
private final String body;
public ServerErrorException(HttpStatus status, String body) {
this.status = status;
this.body = body;
}
}

@ -1,253 +0,0 @@
package cokr.xit.ens.core.utils;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.client.MultipartBodyBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.util.UriComponentsBuilder;
import cokr.xit.ens.core.aop.ApiResponseDTO;
import cokr.xit.ens.core.config.support.WebClientConfig;
import cokr.xit.ens.core.exception.ClientErrorException;
import cokr.xit.ens.core.exception.ErrorParse;
import cokr.xit.ens.modules.kkotalk.model.CmmEnsRlaybsnmDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* <pre>
* description : react Restfull Util
* error(.onStatus) ExchangeFilterFunction {@link WebClientConfig responseFilter}
* packageName : kr.xit.core.spring.util
* fileName : ApiWebClientUtil
* author : julim
* date : 2023-09-06
* ======================================================================
*
* ----------------------------------------------------------------------
* 2023-09-06 julim
*
* </pre>
* @see WebClientConfig
* @see kr.xit.core.spring.config.AsyncExecutorConfig
* @see ClientErrorException
* @see ServerErrorException
* @see ErrorParse
* @see kr.xit.core.spring.config.support.CustomJacksonConfig
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class ApiWebClientUtil {
private static final String AUTH_TYPE_BEARER = "bearer";
private final WebClientConfig webClientConfig;
/**
* WebClient GET
* (.onStatus status.is4xxClientError() || status.is5xxServerError())
* -> {@link WebClientConfig responseFilter}
* @param url String
* @param responseDtoClass Class<T>
* @param headerMap Map<String, String>
* @return responseDtoClass
*/
public <T> T get(final String url, final Class<T> responseDtoClass, Map<String, String> headerMap) {
return webClientConfig.webClient()
.method(HttpMethod.GET)
.uri(url)
.headers(httpHeaders -> getHeaders(httpHeaders, headerMap))
.retrieve()
.bodyToMono(responseDtoClass)
.block();
}
/**
* WebClient POST
* (.onStatus status.is4xxClientError() || status.is5xxServerError())
* -> {@link WebClientConfig responseFilter}
* @param url String
* @param requestDto V
* @param responseDtoClass Class<T>
* @param headerMap Map<String, String>
* @return responseDtoClass
*/
public <T, V> T post(final String url, final V requestDto, final Class<T> responseDtoClass, Map<String, String> headerMap) {
return webClientConfig.webClient()
.method(HttpMethod.POST)
.uri(url)
.headers(httpHeaders -> getHeaders(httpHeaders, headerMap))
.bodyValue(requestDto != null ? requestDto : "")
.retrieve()
.bodyToMono(responseDtoClass)
.block();
}
/**
* kakaotalk WebClient
* (.onStatus status.is4xxClientError() || status.is5xxServerError())
* -> {@link WebClientConfig responseFilter}
* @param url String
* @param method HttpMethod
* @param body Object
* @param rtnClzz Class<T>
* @param ensDTO CmmEnsRlaybsnmDTO
* @return rtnClzz<T>
*/
public <T> T exchangeKkotalk(final String url, final HttpMethod method, final Object body, final Class<T> rtnClzz, final CmmEnsRlaybsnmDTO ensDTO) {
Map<String, String> map = new HashMap<>();
map.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
map.put(HttpHeaders.AUTHORIZATION, String.format("KakaoAK %s", ensDTO.getKakaoDealerRestApiKey()));
map.put("Target-Authorization", String.format("KakaoAK %s", ensDTO.getKakaoPartnerRestApiKey()));
map.put("settle-Id", ensDTO.getKakaoSettleId());
return exchange(url, method, body, rtnClzz, map);
}
/**
* KT-BC WebClient
* (.onStatus status.is4xxClientError() || status.is5xxServerError())
* -> {@link WebClientConfig responseFilter}
* @param url String
* @param method HttpMethod
* @param body Object
* @param rtnClzz Class<T>
* @param ensDTO CmmEnsRlaybsnmDTO
* @return rtnClzz<T>
*/
public <T> T exchangeKt(final String url, final HttpMethod method, final Object body, final Class<T> rtnClzz, final CmmEnsRlaybsnmDTO ensDTO) {
final Map<String,String> headerMap = new HashMap<>();
headerMap.put(HttpHeaders.AUTHORIZATION, String.format("%s %s", AUTH_TYPE_BEARER, ensDTO.getKtAccessToken()));
headerMap.put("client-id", ensDTO.getKtClientId());
headerMap.put("client-tp", ensDTO.getKtClientTp());
return exchange(url, method, body, rtnClzz, headerMap);
}
/**
* KT-GIBIS WebClient
* (.onStatus status.is4xxClientError() || status.is5xxServerError())
* -> {@link WebClientConfig responseFilter}
* @param url String
* @param method HttpMethod
* @param body Object
* @param rtnClzz Class<T>
* @param ensDTO CmmEnsRlaybsnmDTO
* @return rtnClzz<T>
*/
public <T> T exchangeKtGbs(final String url, final HttpMethod method, final Object body, final Class<T> rtnClzz, final CmmEnsRlaybsnmDTO ensDTO) {
final Map<String,String> headerMap = new HashMap<>();
headerMap.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
headerMap.put(HttpHeaders.AUTHORIZATION, String.format("Bearer %s", ensDTO.getKtAccessToken()));
return exchange(url, method, body, rtnClzz, headerMap);
}
/**
* <pre>
* WebClient
* GET url (?key=value&key2=value2)
* (.onStatus status.is4xxClientError() || status.is5xxServerError())
* -> {@link WebClientConfig responseFilter}
* @param url call url
* @param method POST|GET
* @param body JSON String type
* @param rtnClzz rtnClzz return type class
* (ex: new KkopayDocDTO.DocStatusResponse().getClass())
* @return T rtnClzz return DTO
* </pre>
*/
public <T> T exchange(final String url, final HttpMethod method, final Object body, final Class<T> rtnClzz, final Map<String,String> headerMap) {
return webClientConfig.webClient()
.method(method)
.uri(url)
.headers(httpHeaders -> getHeaders(httpHeaders, headerMap))
.bodyValue(body != null ? body : "")
.exchangeToMono(res -> res.bodyToMono(rtnClzz))
.block();
}
/**
* <pre>
* WebClient form data
* -> application/x-www-form-urlencoded
* GET url (?key=value&key2=value2)
* (.onStatus status.is4xxClientError() || status.is5xxServerError())
* -> {@link WebClientConfig responseFilter}
* @param url call url
* @param method POST|GET
* @param body JSON String type
* @param rtnClzz rtnClzz return type class
* (ex: new KkopayDocDTO.DocStatusResponse().getClass())
* @return T rtnClzz return DTO
* </pre>
*/
public <T> T exchangeFormData(final String url, final HttpMethod method, final Object body, final Class<T> rtnClzz, final Map<String,String> headerMap) {
return webClientConfig.webClient()
.method(method)
.uri(url)
.headers(httpHeaders -> getHeaders(httpHeaders, headerMap))
.body(ObjectUtils.isNotEmpty(body)? BodyInserters.fromFormData(JsonUtils.toMultiValue(body)): BodyInserters.empty())
.exchangeToMono(res -> res.bodyToMono(rtnClzz))
.block();
}
/**
* webclient file data
* -> multipart/form-data
* url (?key=value&key2=value2)
* (.onStatus status.is4xxClientError() || status.is5xxServerError())
* -> WebClientConfig.responseFilter()
* @param url
* @param method
* @param files
* @param rtnClzz
* @return rtnClzz
*/
public <T> T exchangeFileData(final String url, final HttpMethod method, final List<MultipartFile> files, final String pFileName, final Class<T> rtnClzz) {
MultipartBodyBuilder builder = new MultipartBodyBuilder();
for(MultipartFile mf : files) {
//builder.part(mf.getOriginalFilename().split("\\.")[0], mf.getResource());
builder.part(pFileName, mf.getResource());
}
return webClientConfig.webClient()
.method(method)
.uri(url)
.contentType(MediaType.MULTIPART_FORM_DATA)
.body(BodyInserters.fromMultipartData(builder.build()))
.exchangeToMono(res -> res.bodyToMono(rtnClzz))
.block();
// .blockOptional()
// .orElse("");
}
public <T> ApiResponseDTO<T> sendError(final Throwable e) {
return ErrorParse.extractError(e.getCause());
}
private URI createUrl(final String endPoint, final String... value) {
return UriComponentsBuilder.fromUriString(endPoint)
.build(value);
}
private HttpHeaders getHeaders(final HttpHeaders headers, final Map<String, String> map) {
if(ObjectUtils.isEmpty(map)) return headers;
for(Map.Entry<String, String> e : map.entrySet()){
headers.add(e.getKey(), e.getValue());
}
return headers;
}
}

@ -1,285 +0,0 @@
// package cokr.xit.ens.modules.kkotalk;
//
// import java.nio.charset.StandardCharsets;
// import java.security.InvalidAlgorithmParameterException;
// 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.ArrayList;
// import java.util.Base64;
// import java.util.List;
// import java.util.Locale;
// import java.util.Random;
// import java.util.Set;
// import java.util.UUID;
//
// import javax.crypto.BadPaddingException;
// import javax.crypto.Cipher;
// import javax.crypto.IllegalBlockSizeException;
// import javax.crypto.Mac;
// import javax.crypto.NoSuchPaddingException;
// import javax.crypto.SecretKey;
// import javax.crypto.spec.IvParameterSpec;
// import javax.crypto.spec.SecretKeySpec;
// import javax.validation.ConstraintViolation;
// import javax.validation.Validation;
// import javax.validation.Validator;
//
// import org.apache.commons.lang3.ObjectUtils;
// import org.apache.commons.lang3.StringUtils;
// import org.springframework.util.Base64Utils;
//
// import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ErrorMsg;
//
// import cokr.xit.ens.core.exception.BizRuntimeException;
// import cokr.xit.ens.core.utils.CoreSpringUtils;
// import cokr.xit.ens.core.utils.MessageUtil;
// import cokr.xit.ens.modules.kkotalk.model.CmmEnsRequestDTO;
// import cokr.xit.ens.modules.kkotalk.model.CmmEnsRlaybsnmDTO;
// import lombok.AccessLevel;
// import lombok.NoArgsConstructor;
//
// /**
// * <pre>
// * description : ENS 공통 method
// *
// * packageName : kr.xit.ens.cmm
// * fileName : CmmNiceCiUtils
// * author : limju
// * date : 2023-09-19
// * ======================================================================
// * 변경일 변경자 변경 내용
// * ----------------------------------------------------------------------
// * 2023-09-19 limju 최초 생성
// *
// * </pre>
// */
//
// @NoArgsConstructor(access = AccessLevel.PRIVATE)
// public class CmmEnsUtils {
// private static final MessageUtil messageUtil = CoreSpringUtils.getMessageUtil();
// private static final ICmmEnsCacheService cacheService = ApiSpringUtils.getCmmEnsCacheService();
// private static final IBizKtBcService bizKtService = ApiSpringUtils.getBizKtMmsService();
//
// /**
// * 문서 중개자 인증 정보 조회
// * @param signguCode string
// * @param ffnlgCode String
// * @param seCode SndngSeCode 문서중개자 구분 코드
// * @return CmmEnsRlaybsnmDTO 문서중개자 정보
// */
// public static CmmEnsRlaybsnmDTO getRlaybsnmInfo(final String signguCode, final String ffnlgCode, final
// SndngSeCode seCode) {
// CmmEnsRequestDTO ensDTO = CmmEnsRequestDTO.builder()
// .signguCode(signguCode)
// .ffnlgCode(ffnlgCode)
// .profile(ApiConstants.IS_PROFILE_LOCAL? "local" : "prod")
// .build();
//
// final CmmEnsRlaybsnmDTO dto = cacheService.getRlaybsnmInfoCache(ensDTO);
// if(ObjectUtils.isEmpty(dto)) throw BizRuntimeException.create(messageUtil.getMessage("fail.api.rlaybsnm.info"));
//
// // KT인 경우 토큰유효기간 check
// if(SndngSeCode.KT_BC.equals(seCode)){
//
// if(StringUtils.isNotEmpty(dto.getKtTokenExpiresIn())
// && DateUtils.getTodayAndNowTime(ApiConstants.FMT_DT_STD).compareTo(dto.getKtTokenExpiresIn()) < 0
// && ObjectUtils.isNotEmpty(dto.getKtAccessToken())
// ) return dto;
//
// // 유효기간이 경과된 경우 재발급
// bizKtService.requestToken(
// KtMnsRequest.builder()
// .signguCode(signguCode)
// .ffnlgCode(ffnlgCode)
// .profile(ApiConstants.IS_PROFILE_LOCAL? "local" : "prod")
// .build()
// );
// return cacheService.getRlaybsnmInfoCache(ensDTO);
// }
// return dto;
// }
//
// /**
// * <pre>
// * parameter validation check
// * invalid parameter message -> String으로 BizRuntimeException throw
// * @param t T
// * </pre>
// */
// public static <T> void validate(T t) {
// Locale.setDefault(Locale.KOREA);
// final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
// final Set<ConstraintViolation<T>> list = validator.validate(t);
//
// if (!list.isEmpty()) {
// throw BizRuntimeException.create(
// list.stream()
// .map(row -> String.format("%s=%s", row.getPropertyPath(), row.getMessageTemplate()))
// //.map(row -> String.format("%s=%s", row.getPropertyPath(), row.get()) ? row.getMessage(): row.getMessageTemplate()))
// .toList().toString());
// }
// }
//
// /**
// * parameter validation check
// * @param t T
// * @return List<ErrorMsg>
// */
// public static <T> List<ErrorMsg> getValidateErrors(T t) {
// Locale.setDefault(Locale.KOREA);
// final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
// final Set<ConstraintViolation<T>> list = validator.validate(t);
//
// if (!list.isEmpty()) {
// return list.stream()
// .map(row -> new ErrorMsg(String.format("%s=%s", row.getPropertyPath(), row.getMessageTemplate())))
// .toList();
// }
// return new ArrayList<>();
// }
//
// /**
// * length 길이의 UUID String return -> '-' remove
// * @param length
// * @return
// */
// public static String generateLengthUuid(int length) {
// final String allChars = UUID.randomUUID().toString().replace("-", "");
// final Random random = new Random();
// final char[] otp = new char[length];
// for (int i = 0; i < length; i++) {
// otp[i] = allChars.charAt(random.nextInt(allChars.length()));
// }
// return String.valueOf(otp);
// }
//
// /**
// * 공개키로 암호화를 수행
// *
// * @param publicKeyString String
// * @param symkeyRegInfo String
// * @return String
// */
// public static String encSymkeyRegInfo(String publicKeyString, String symkeyRegInfo) {
// try {
// KeyFactory keyFactory = KeyFactory.getInstance("RSA");
// byte[] cipherEnc = Base64.getDecoder().decode(publicKeyString);
// 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(symkeyRegInfo.getBytes());
//
// return Base64Utils.encodeToString(bytePlain);
// } catch (NoSuchAlgorithmException | InvalidKeySpecException | NoSuchPaddingException |
// IllegalBlockSizeException | BadPaddingException | InvalidKeyException e){
// throw BizRuntimeException.create(e.getMessage());
// }
// }
//
// /**
// * sha256 암호화
// *
// * @param text String
// * @return String
// */
// public static String hexSha256(final String text) {
// final StringBuilder sbuf = new StringBuilder();
//
// try {
// final MessageDigest mDigest = MessageDigest.getInstance("SHA-256");
// mDigest.update(text.getBytes());
//
// final byte[] msgStr = mDigest.digest();
//
// for(final byte tmpStrByte : msgStr) {
// final String tmpEncTxt = Integer.toString((tmpStrByte & 0xff) + 0x100, 16)
// .substring(1);
//
// sbuf.append(tmpEncTxt);
// }
// } catch (NoSuchAlgorithmException nae){
// throw BizRuntimeException.create(nae.getMessage());
// }
// return sbuf.toString();
// }
//
//
// /**
// * <pre>
// * AES 암호화 -> Base64 encoding return
// * -> Nice ci 데이타 암호화
// *
// * @param key String
// * @param iv String
// * @param planText String
// * @return String Base64 encoding data
// * </pre>
// */
// public static String encodeAesData(final String key, final String iv, final String planText) {
// final SecretKey secureKey = new SecretKeySpec(key.getBytes(), "AES");
// try {
// final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// cipher.init(Cipher.ENCRYPT_MODE, secureKey, new IvParameterSpec(iv.getBytes()));
//
// final byte[] encData = cipher.doFinal(planText.trim().getBytes(StandardCharsets.UTF_8));
// return Base64.getEncoder().encodeToString(encData);
//
// }catch (NoSuchPaddingException | NoSuchAlgorithmException |
// InvalidAlgorithmParameterException | InvalidKeyException |
// IllegalBlockSizeException | BadPaddingException e){
// throw BizRuntimeException.create(e.getMessage());
// }
// }
//
// /**
// * <pre>
// * Hmac 무결성체크값(integrity_value) 생성
// * @param hmacKey String
// * @param message String
// * @return String
// * </pre>
// */
// public static String encodeHmacSha256(final String hmacKey, final String message) {
// try {
// final Mac mac = Mac.getInstance("HmacSHA256");
// final SecretKeySpec sks = new SecretKeySpec(hmacKey.getBytes(), "HmacSHA256");
// mac.init(sks);
// final byte[] hmac256 = mac.doFinal(message.getBytes());
// return Base64.getEncoder().encodeToString(hmac256);
//
// }catch (NoSuchAlgorithmException|InvalidKeyException e){
// throw BizRuntimeException.create(e.getMessage());
// }
// }
//
// /**
// * AES 복호화
// * @param encData String
// * @param key String
// * @param iv String
// * @return String
// */
// public static String decodeAesData(String encData, String key, String iv) {
//
// final byte[] respDataEnc = Base64.getDecoder().decode(encData.getBytes());
// final SecretKey secureKey = new SecretKeySpec(key.getBytes(), "AES");
//
// try {
// final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// cipher.init(Cipher.DECRYPT_MODE, secureKey, new IvParameterSpec(iv.getBytes()));
// final byte[] decrypted = cipher.doFinal(respDataEnc);
// return new String(decrypted);
//
// }catch (NoSuchPaddingException | NoSuchAlgorithmException |
// InvalidAlgorithmParameterException | InvalidKeyException |
// IllegalBlockSizeException | BadPaddingException e){
// throw BizRuntimeException.create(e.getMessage());
// }
// }
// }

@ -1,67 +0,0 @@
package cokr.xit.ens.modules.kkotalk.model;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.media.Schema.RequiredMode;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
/**
* <pre>
* description : Request DTO
*
* packageName : kr.xit.biz.ens.model.kt
* fileName : CmmEnsRequestDTO
* author : limju
* date : 2023-09-22
* ======================================================================
*
* ----------------------------------------------------------------------
* 2023-09-22 limju
*
* </pre>
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@SuperBuilder
@JsonInclude(Include.NON_NULL)
public class CmmEnsRequestDTO {
/**
*
*/
@Schema(requiredMode = RequiredMode.REQUIRED, title = "시군구코드", example = "51110")
@Size(min = 1, max = 10, message = "시군구 코드는 필수 입니다")
@JsonProperty("signguCode")
private String signguCode;
/**
*
*/
@Schema(requiredMode = RequiredMode.REQUIRED, title = "과태료코드", example = "11")
@Size(min = 1, max = 2, message = "과태료 코드는 필수 입니다")
@JsonProperty("ffnlgCode")
private String ffnlgCode = "11";
/**
* active profile
*/
@Schema(requiredMode = RequiredMode.AUTO, title = "profile", example = "local")
@JsonProperty("profile")
private String profile;
/**
* 1
*/
@Schema(hidden = true, requiredMode = RequiredMode.AUTO, title = "1차 발송", example = "KKO-MY-DOC")
@JsonProperty("try1")
private String try1;
}

@ -1,174 +0,0 @@
package cokr.xit.ens.modules.kkotalk.model;
import java.io.Serializable;
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;
/**
* <pre>
* description : DTO
*
* packageName : kr.xit.biz.ens.model.kt
* fileName : KtMmsDTO
* author : limju
* date : 2023-09-22
* ======================================================================
*
* ----------------------------------------------------------------------
* 2023-09-22 limju
*
* </pre>
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class CmmEnsRlaybsnmDTO implements Serializable {
private static final long serialVersionUID = 1L;
/**
*
*/
private String signguCode;
/**
*
*/
private String ffnlgCode;
/**
* profile
*/
private String profile;
/**
*
*/
private String signguNm;
/**
*
*/
private String ffnlgNm;
/**
* KAKAO CLIENT ID
*/
private String kakaoClientId;
/**
* KAKAO
*/
private String kakaoProductCd;
/**
* KAKAO ACCESS TOKEN
*/
private String kakaoAccessToken;
/**
* KAKAO CONTRACT UUID
*/
private String kakaoContractUuid;
/**
* KAKAO_NEW PARTNER KEY
*/
private String kakaoPartnerRestApiKey;
/**
* KAKAO_NEW DEALER KEY
*/
private String kakaoDealerRestApiKey;
/**
* KAKAO_NEW SETTLE ID
*/
private String kakaoSettleId;
/**
* KT client id
*/
private String ktClientId;
/**
* KT client tp
*/
private String ktClientTp;
/**
* KT Scope
*/
private String ktScope;
/**
* KT Service code
*/
private String ktServiceCode;
/**
* KT service client ID
*/
private String ktSvcClientId;
/**
* KT service client secret
*/
private String ktSvcClientSecret;
/**
* KT service cerf key
*/
private String ktSvcCerfKey;
/**
* KT_ACCESS_TOKEN
*/
private String ktAccessToken;
/**
* KT
*/
private String ktTokenExpiresIn;
/**
* KT
*/
private String ktTokenJti;
/**
* postplus apiKey
*/
private String pplusApiKey;
/**
* EPost service key
*/
private String epostServiceKey;
/**
*
*/
private String senderNm;
/**
*
*/
private String senderZipNo;
/**
*
*/
private String senderAddr;
/**
*
*/
private String senderDetailAddr;
/**
*
*/
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonFormat(pattern = "yyyy-MM-dd kk:mm:ss")
private LocalDateTime registDt;
/**
*
*/
private String register;
/**
*
*/
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonFormat(pattern = "yyyy-MM-dd kk:mm:ss")
private LocalDateTime updtDt;
/**
*
*/
private String updusr;
}
Loading…
Cancel
Save