package com.eactive.eai.adapter.http.client.impl;

import java.io.IOException;
import java.io.StringReader;
import java.math.BigDecimal;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

// encrypt test by jwhong
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.hc.client5.http.classic.HttpClient;
import org.apache.hc.client5.http.classic.methods.HttpDelete;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPatch;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.classic.methods.HttpPut;
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.apache.hc.core5.http.protocol.BasicHttpContext;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.apache.hc.core5.net.URIBuilder;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import com.eactive.eai.adapter.AdapterPropManager;
import com.eactive.eai.adapter.http.HttpMemoryLogger;
import com.eactive.eai.adapter.http.HttpMethodType;
import com.eactive.eai.adapter.http.client.HttpClient5AdapterServiceSupport;
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
import com.eactive.eai.adapter.http.client.HttpClientAdapterVO;
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
import com.eactive.eai.authserver.service.OAuth2Manager;
import com.eactive.eai.common.TransactionContextKeys;
import com.eactive.eai.common.authoutbound.AccessTokenManagerByDB;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.message.MessageType;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.util.CommonLib;
import com.eactive.eai.common.util.JSONUtils;
import com.eactive.eai.common.util.TxFileLogger;
import com.eactive.eai.common.util.XMLUtils;
import com.eactive.eai.util.JsonPathUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.kjbank.encrypt.exchange.crypto.AES256Cipher;
import com.kjbank.encrypt.exchange.crypto.AES256GCMCipher;
import com.kjbank.encrypt.exchange.crypto.AESCipher;
import com.kjbank.encrypt.exchange.crypto.ECDHESA256Cipher;
import com.nimbusds.jwt.SignedJWT;
import com.openbanking.eai.common.token.AccessTokenManager;
import com.openbanking.eai.common.token.AccessTokenVO;
import com.openbanking.eai.common.token.OAuth2AccessTokenVO;

import edu.emory.mathcs.backport.java.util.Arrays;

/**
 * 1. 기능 : EAI HTTP OutBound 용 어댑터로 수동 시스템의 HTTP 웹 컴포넌트를 GET/POST 방식으로 호출할 수 있는
 * 기능을 제공한다.<br>
 * 2. 처리 개요 : <br>
 * * - 2020-09-25: Http Header 받아서 처리할 수 있게 기능 추가<br>
 * 3. 주의사항 <br> 
 *
 * @author :
 * @version : v 1.0.0
 * @see : HttpClientAdapterServiceFactory.java,
 *      HttpClientAdapterServiceSupport.java
 * @since :
 *
 */
public class HttpClient5AdapterServiceRest extends HttpClient5AdapterServiceSupport
		implements HttpClientAdapterServiceKey {
	public static final String TYPE_VARIABLE_URL_REQUEST = "variableUrlRequest";
	public static final String TYPE_SIMPLE_REQUEST = "simpleRequest";
	public static final String REST_OPTION = "REST_OPTION";
	//public static final String HEADER_CONTENT_TYPE = "Content-Type";
	public static final String HEADER_GROUP = "HEADER_GROUP";
	public static final String HTTP_STATUS = "HTTP_STATUS";
	public static final String HEADER_KEYS = "HEADER_KEYS";
	public static final String AUTH_TOKEN = "AUTH_TOKEN";
	public static final String HTTP_HEADER_SETTING = "HTTP_HEADER_SETTING";

	public static final String PAYLOAD_PARAM_NAME_CLIENT_ID = "client_id";  // jwhong
	
	static final String DJB_ROOTLESS_ARRAY = "{ \"DJB_ROOTLESS_ARRAY\" : ";

	private boolean useAdapterToken;
	private boolean encryptResponseApply;
	private String httpHeaderSettingByAdapter = "{}";

	/**
	 * 1. 기능 : REST API 통신에 사용 <br>
	 * 2. 처리 개요 : - 속성 정보를 설정 하고 수동 시스템 서비스를 호출 한다. <br>
	 * 3. 주의사항 <br>
	 *
	 * @param prop    Http Adapter 속성 정보
	 * @return 반환 된 Object
	 * @exception Exception 수동 시스템 간 통신 중 발생
	 **/
	@SuppressWarnings({ "unchecked" })
	public Object execute(Properties prop, Object data, Properties tempProp) throws Exception {
		HttpClientAdapterVO vo = super.setting(prop, tempProp);

		// 2025.04.09 Authorization 헤더값을 프로퍼티(AUTH_TOKEN)에서 지정하여 설정할 수 있도록 수정
		// 2025.05.29 프로퍼티 그룹 AUTH_TOKEN이 없을때 Null Point Exception 발생하여 수정
		String bizCode = "";
		String headerGroupName = prop.getProperty(HEADER_GROUP);
		String relayResponseHeaderKeys = prop.getProperty(HEADER_KEYS, "");
		useAdapterToken = StringUtils.equalsIgnoreCase(prop.getProperty("ADAPTER_TOKEN_USE_YN", "N"), "Y");
		String authorizationHeaderName = prop.getProperty("ADAPTER_TOKEN_HEADER_NAME", "Authorization");
		
		boolean useForwardProxy = StringUtils.equalsIgnoreCase(prop.getProperty("FORWARD_PROXY_USE_YN", "N"), "Y");
		String forwardProxyUrl = prop.getProperty("FORWARD_PROXY_URL");

		// ex) $.dataHeader.GW_RSLT_CD
		String tokenErrorCodeKey = prop.getProperty("ADAPTER_TOKEN_ERROR_CODE_KEY");
		String tokenErrorCodeValues = prop.getProperty("ADAPTER_TOKEN_ERROR_CODE_VALUES");
		String tokenErrorHttpStatusCode = prop.getProperty("ADAPTER_TOKEN_ERROR_HTTP_STATUS_CODE"); // 200 or 400번대

		// 레이아웃 메시지 타입 REST URL 추출 시 활용. Default JSON
		String messageType = prop.getProperty("MESSAGE_TYPE", MessageType.JSON);
		String inboundMethod = tempProp.getProperty(HttpAdapterServiceKey.INBOUND_METHOD, "POST");
		//String inboundToken = tempProp.getProperty(HttpAdapterServiceKey.INBOUND_TOKEN, "");

		//Outbound 요청에 대한 응답 메시지의 복호화 여부 결정위해 jwhong
		encryptResponseApply = StringUtils.equalsIgnoreCase(prop.getProperty("ENCRYPT_RESPONSE_APPLY", "N"), "Y");
		
		//업체 300응답시 특정 http status code 경우 에러 아닌걸로 처리. 광주은행
		String errIgnore = prop.getProperty("ERROR_IGNORE_CODE", "");

		/**
		 * @formatter:off
		 * TSEAIHE02.RESTOPTION 정보 => JSON 형태로 구성
		 * - type : simpleRequest, variableUrlRequest
		 * - extraPath : 어댑터 프로퍼티 URL에 추가될 HTTP REST URL
		 * - method : get, delete, post, put
		 * - contentType: application/json(default), application/x-www-form-urlencoded
		 * - adapterTokenUseYn: Y, N(default)
		 * ex)
		 * {"type":"simpleRequest","extraPath":"v2.0/accout/balance","method":"post"}
		 * @formatter:on
		 */

		String restOptionData = tempProp.getProperty(REST_OPTION);

		JSONObject restOptionObject = parseJson(restOptionData);
		if (restOptionObject == null) {
			throw new Exception("OptionData parsing result is NULL");
		}

		String rmethod = (String) restOptionObject.getOrDefault("method", inboundMethod);
		String contentType = (String) restOptionObject.getOrDefault("contentType", "application/json");
		
		ContentType oContentType = ContentType.parse(contentType);
		Charset contentTypeCharset = oContentType.getCharset();
		String charset = vo.getEncode();
		if(contentTypeCharset != null)
			charset = contentTypeCharset.displayName();
		
		logger.debug("HttpClient5AdapterServiceRest] charset = {}", charset);
		
		String mimeType = oContentType.getMimeType();
		
		String adapterTokenUseYn = (String) restOptionObject.get("adapterTokenUseYn");
		if (StringUtils.isNotBlank(adapterTokenUseYn)) { // interface 에 설정된게 우선한다.
			useAdapterToken = StringUtils.equalsIgnoreCase(adapterTokenUseYn, "Y");
		}
		
		String cnkUseYn = (String) restOptionObject.get("cnkUseYn");
		boolean chunked = false;
		if (StringUtils.isNotBlank(cnkUseYn)) {
			chunked =  StringUtils.equalsIgnoreCase(cnkUseYn, "Y");
		}

		HttpClient mclient = this.client;
		Object sendData = "";
		if (data instanceof String) {
			sendData = data;
		} else if (data instanceof byte[]) {
			sendData = new String((byte[]) data, vo.getEncode());
		} else if (data instanceof JSONObject) {
			sendData = data;
		}

		////mclient.getParams().setContentCharset(vo.getEncode());

		Object dataObject = null;
		Object httpHeader = null;
		//Object dataContent = null;

		if (MessageType.JSON.equals(messageType)) {
			Object parsed = JSONUtils.parseJsonGeneric(sendData);
			if(parsed instanceof JSONObject) {
				JSONObject jsonObject = (JSONObject) parsed;
				dataObject = jsonObject;
				
			} else if(parsed instanceof JSONArray) {
				// not support
			}
		} else if (MessageType.XML.equals(messageType)) {
			Document doc = XMLUtils.convertXmlDocument(sendData);
			dataObject = doc;
		}

//		if (MessageType.JSON.equals(messageType)) {
//			dataObject = parseJson(sendData);
//			if (dataObject != null && StringUtils.isNotBlank(headerGroupName)) {
//				httpHeader = dataObject.get(headerGroupName);
//				dataObject.remove(headerGroupName);
//			}
//		}

		logger.debug("HttpClientAdapterServiceRest] dataObject1 =  [" + dataObject + "]");

		// Path Variable 처리를 위해 Inbound에서 전달한 Variable Map
		Map<String, String> inboundPathVariables = (Map<String, String>) tempProp.get(HttpAdapterServiceKey.INBOUND_PATH_VARIABLES);
		// interface 에 설정된게 우선한다.
		String uri = null;
		if(this.isTas(tempProp)) {
			uri = vo.getUrl();
		} else {
			if (dataObject == null) {
				uri = changeUrl(messageType, vo.getUrl(), restOptionData, sendData, inboundPathVariables);
			} else {
				uri = changeUrl(messageType, vo.getUrl(), restOptionData, dataObject, inboundPathVariables);
			}
		}
		
		if(dataObject instanceof JSONObject) {
			if (dataObject != null && StringUtils.isNotBlank(headerGroupName)) {
				httpHeader = ((JSONObject)dataObject).get(headerGroupName);
				((JSONObject)dataObject).remove(headerGroupName);
			}
		} else if (dataObject instanceof Document) {
			Document doc = (Document)dataObject;
			if (doc != null && StringUtils.isNotBlank(headerGroupName)) {
				Element root = doc.getRootElement();
				Element httpHeaderElement = root.element(headerGroupName);
				root.remove(httpHeaderElement);
				httpHeader = httpHeaderElement;
			}
		}

		logger.debug("HttpClientAdapterServiceRest] dataObject2 =  [" + dataObject + "]");

//		////if (vo.getConnectionTimeout() != 0) {
//			mclient.getHttpConnectionManager().getParams().setConnectionTimeout(vo.getConnectionTimeout());
//		}

		if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
			logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") URL=[" + vo.getUrl() + "] ");
			logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") PARAMETER_NAME=[" + vo.getParameterName() + "] ");
			logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") ENCODE=[" + vo.getEncode() + "] ");
			logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") RESPONSE_TYPE=[" + vo.getResponseType() + "] ");
			logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") URL_ENCODE_YN=[" + vo.getUrlEncodeYn() + "] ");
			logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") CONNECTION_TIMEOUT=[" + vo.getConnectionTimeout() + "] ");
			logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") REST_OPTION=["	+ restOptionData + "] ");
		}

		HttpUriRequestBase method = null;


		// 메소드 타입에 따라 HttpRequestBase 인스턴스 생성
		switch (HttpMethodType.getValue(rmethod)) {
			case GET:
				method = new HttpGet(uri);
				break;
			case DELETE:
				method = new HttpDelete(uri);
				break;
			case POST:
				method = new HttpPost(uri);
				break;
			case PUT:
				method = new HttpPut(uri);
				break;
			case PATCH:
				method = new HttpPatch(uri);
				break;
			default:
				method = new HttpGet(uri);
				break;
		}

		RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();

		if(useForwardProxy && !isTas(tempProp)) {
			java.net.URL url = new java.net.URL(forwardProxyUrl);

			// 프로토콜, 호스트, 포트 추출
			HttpHost proxy = new HttpHost(url.getProtocol(), url.getHost(), url.getPort());
			requestConfigBuilder.setProxy(proxy);
		}

		// OAuth2AccessToken check 부분을 뒤에서 여기로 위치를 옮김, 나이스지키미 암호화 KEY를 얻기 위해서. JWHONG
		OAuth2AccessTokenVO accessToken = null;
		if (useAdapterToken) {
			AccessTokenManagerByDB tokenManager = AccessTokenManagerByDB.getInstance();
			accessToken = (OAuth2AccessTokenVO) tokenManager.getAccessTokenVO(vo.getAdapterGroupName());

			// 토큰이 없거나 만료 됐으면 재발급
			//if (accessToken == null || accessToken.isExpired()) {
			if (accessToken == null || accessToken.isExpired() || accessToken.getAccessToken() == null ) {    // jwhong
				String oldToken = accessToken == null ? null : accessToken.getAccessToken();
				accessToken = (OAuth2AccessTokenVO) tokenManager.retryAccessTokenVO(vo.getAdapterGroupName(), prop,
						oldToken);
			}

			if (logger.isDebug()) {
				logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") TOKEN = ["
						+ accessToken + "]");
			}

			setAuthHeaders(method, accessToken, authorizationHeaderName);

			if (logger.isDebug()) {
				logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName()
						+ ") RequestHeader [" + method.getHeader(authorizationHeaderName).getName() + ": " + method.getHeader(authorizationHeaderName).getValue() + "]");
			}
		}
		
		// 업무별 고정 token
		String authToken = "";
		try {
			Properties authProp = PropManager.getInstance().getProperties(AUTH_TOKEN); //Authorization
			bizCode = vo.getAdapterGroupName().substring(1, 4);
			authToken = authProp.getProperty(bizCode, "");
		} catch (Exception e) {
			logger.debug("Property Group AUTH_TOKEN is not Exist !!");
		}

		logger.debug("authToken :::::::::::::::::::::::::::::::::::" + authToken);

		if(!StringUtils.isBlank(authToken)) {
			setAuthHeaders(method, authToken, authorizationHeaderName);
		}
		// 여기 까지

		configureHttpClient(requestConfigBuilder, vo, method);
		assignFilterHeaders(method, tempProp); // OutBound PreFilter에서 설정한 Header내용 설정.

		switch (HttpMethodType.getValue(rmethod)) {
			case GET:
			case DELETE:
				HashMap<String, String> h = getParameters(dataObject);
				URIBuilder uriBuilder = new URIBuilder(uri);
				for (Map.Entry<String, String> entry : h.entrySet()) {
					uriBuilder.addParameter(entry.getKey(), entry.getValue());
				}
				URI fullUri = uriBuilder.build();
				if (method instanceof HttpGet) {
					((HttpGet) method).setUri(fullUri);
				} else if (method instanceof HttpDelete) {
					((HttpDelete) method).setUri(fullUri);
				}
				if (logger.isDebug()) {
					logger.debug("HttpClientAdapterServiceRest] (get Method) QueryString = [" + fullUri.getQuery() + "]");
				}
				break;
			case PUT:
			case POST:
			case PATCH:
//					assignPostBody(dataObject, contentType, vo.getEncode(), method);
				//assignPostBody(dataContent, contentType, vo.getEncode(), method);  // jwhong commnet
				// KJBank API 추적정보를 Header에 제공. jwhong
//				String inboundToken= assignRequestKJHeaders(method, prop, tempProp );
				assignPostBody(dataObject, mimeType, charset, method, chunked);
				break;
			default:
				break;
		}

		if (logger.isDebugEnabled()) {
			logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") method.getParams()=["
					+ method.getEntity() + "] ");
		}

		// OAuth2AccessToken 원래 있던 위치  JWHONG

		// 전달 header 셋팅
		// Adapter 레벨 header 보다 data로 넘어온 httpHeader를 우선 적용(header명이 같다면 덮어씀)
		assignRequestHeaders(method, httpHeader, prop);

		int status = -1;

		Header[] responseHeaders = null;
		String responseString = null;
		try {
			byte[] responseMessage = null;
//			byte[] responseMessageOri = null;
			String responseContentType = null;

			if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
				if (dataObject instanceof JSONObject) {
					logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = ["
							+ ((JSONObject)dataObject).toJSONString() + "]");
					logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = "
							+ CommonLib.getDumpMessage(((JSONObject)dataObject).toJSONString()));
				} else {
					logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = [" + sendData
							+ "]");
					logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = "
							+ CommonLib.getDumpMessage(sendData));
				}
			}
			StopWatch stopWatch = new StopWatch();
			stopWatch.start();

			if (vo.getTraceLevel() >= 3) {
				HttpMemoryLogger.txlog(vo.getAdapterGroupName() + vo.getAdapterName(),
						"SEND [" + sendData + "]" + CommonLib.getDumpMessage(sendData));
			}
			
			TxFileLogger.logTxFile(tempProp, sendData, "[OUT_SEND]");

			String uuid = tempProp.getProperty(TransactionContextKeys.TRANSACTION_UUID);
			HttpContext context = new BasicHttpContext();
			context.setAttribute(TransactionContextKeys.TRANSACTION_UUID, uuid);
			context.setAttribute(HttpClientAdapterServiceKey.ADAPTER_GROUP_NAME, vo.getAdapterGroupName());
			context.setAttribute(HttpClientAdapterServiceKey.ADAPTER_NAME, vo.getAdapterName());
			Integer logProcessNo = (Integer) tempProp.get(HttpClientAdapterServiceKey.LOG_PROCESS_NO);
			if (logProcessNo != null && logProcessNo > 0) {
				context.setAttribute(HttpClientAdapterServiceKey.LOG_PROCESS_NO, logProcessNo);
			}

			// encrypt algorithm type 추출 from adapter property jwhong
//			Properties properties = AdapterPropManager.getInstance().getProperties(vo.getAdapterName()); // jwhong
//			String encryptAlgorithm = properties.getProperty("ENCRYPT_ALGORITHM");   // jwhong

			try {
				if (logger.isDebug()) {
					logger.debug("[method getName]" + method.getMethod());
					logger.debug("[method getEntity]" + method.getEntity());
					logger.debug("[method getRequestHeaders]" + method.getHeaders().toString());
					logger.debug("[method getURI]" + method.getPath());
				}
				
				// executor 생성 (mclient, timeout은 기존 설정 그대로)
				DeadlineAwareRetryExecutor executor =
				    new DeadlineAwareRetryExecutor((CloseableHttpClient)mclient,
				                                   vo.getConnectionTimeout(),
				                                   vo.getTimeout());

				// Properties에서 RetryPolicy 로드
				RetryPolicy policy = RetryPolicy.from(prop); // 설정 로드 방식에 맞게
				try (CloseableHttpResponse response = (CloseableHttpResponse) executor.execute(method, context, policy)) {
//				try (CloseableHttpResponse response = (CloseableHttpResponse) mclient.execute(method, context)) {
					status = response.getCode();

					//responseMessage = EntityUtils.toByteArray(response.getEntity());
					// 역기서 responseMessage를 decryption 해야 하나 by jwhong

					responseMessage = EntityUtils.toByteArray(response.getEntity());
					logger.debug("[responseMessage 바이트 배열 길이 ]" + responseMessage.length);

//					responseMessage = doOutboundPostFilter(responseMessageOri, encryptAlgorithm, vo.getAdapterName(), accessToken); // jwhong
					// 여기까지

					responseHeaders = response.getHeaders();
					Header headerContentType = response.getHeader("Content-Type");
					if(headerContentType != null) {
						responseContentType = headerContentType.getValue();
					}
					
					if(responseContentType == null)
						responseContentType = ContentType.APPLICATION_JSON.getMimeType();
					
					tempProp.setProperty("RES_CONTENT_TYPE", responseContentType);
					
					TxFileLogger.logTxFile(tempProp, new String(responseMessage,  vo.getEncode()), "[OUT_RECV]");

					if (logger.isDebug()) {
						logger.debug("[received status]" + status);
						logger.debug("HttpClientAdapterServiceRest] RECV (" + vo.getAdapterGroupName() + ") = [" + responseMessage + "]");
					}
					
				}
			} catch (ConnectException e) {
				if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
					logger.debug("HttpClientAdapterServiceRest] responseType =" + vo.getResponseType());
				}
				throw new Exception("excuteMethod java.net.ConnectException = " + e.getMessage());
			}

			stopWatch.stop();

			/**
			 * @formatter:off
			 * OAuth 토큰 응답 체크(Adapter properties로 설정)
			 * 응답코드에 따라 유효한 토큰 확인(토큰 재발급 여부 확인)
			 * API 서비스 마다 정책이 다름(보통 400대에서 체크하나 200에서도 체크할 수 있음)
			 *
			 * TOKEN_ERROR_CODE_KEY: 응답 json error code key
			 * __ex) $.dataHeader.resultCode
			 * TOKEN_ERROR_CODE_VALUES: 토큰 재발급이 필요한 응답 error codes(ex: O0001,O0002,O0003)
			 * TOKEN_ERROR_HTTP_STATUS_CODE: 보통 400대에서 체크하나 API 제공자에 따라 200에서도 체클할수 있음
			 * ex) TOKEN_ERROR_HTTP_STATUS_CODE = 200
			 * @formatter:on
			 */
			boolean needReissue = false;

			responseString = new String(responseMessage, vo.getEncode());

			if (isStatusInIgnore(status,errIgnore )) {
				// 이경우 정상으로 처리함
			} else if (status >= 200 && status <= 207) {
				if (useAdapterToken && StringUtils.equals(tokenErrorHttpStatusCode, "200")) {
					needReissue = checkTokenRetry(responseMessage, tokenErrorCodeKey, tokenErrorCodeValues,
							vo.getEncode());
				}
			} else if (status == 302) {
				if (!StringUtils.contains(relayResponseHeaderKeys, "Location")) {
					relayResponseHeaderKeys += ",Location";
				}
			} else {
				String errMsg = String.format(
						"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s  response Data=%s",
						status, vo.getAdapterGroupName(), vo.getAdapterName(), uri, rmethod, responseString);
//				logger.error(errMsg);

				if (status >= 400 && status < 500) {
					if (useAdapterToken) {
						needReissue = checkTokenRetry(responseMessage, tokenErrorCodeKey, tokenErrorCodeValues,
								vo.getEncode());
					}

					if (!needReissue) {
						throw new Exception(errMsg);
					}
				} else {

					throw new Exception(errMsg);
				}
			}

			// ----------------------------------------------------------
			if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
				logger.debug("HttpClientAdapterServiceRest] responseType =" + vo.getResponseType());
				logger.debug("HttpClientAdapterServiceRest] RECV " + vo.getEncode() + "(" + vo.getAdapterGroupName() + ") = [" + new String(responseMessage, vo.getEncode()) + "]");
//				logger.debug("HttpClientAdapterServiceRest] RECV MS949 (" + vo.getAdapterGroupName() + ") = ["	+ new String(responseMessage, "MS949") + "]");
//				logger.debug("HttpClientAdapterServiceRest] RECV euc-kr (" + vo.getAdapterGroupName() + ") = [" + new String(responseMessage, "euc-kr") + "]");
				logger.debug("HttpClientAdapterServiceRest] RECV (" + vo.getAdapterGroupName() + ") = " + CommonLib.getDumpMessage(responseMessage));
			}

			if (useAdapterToken) {
				if (responseMessage == null) {
					throw new Exception("responseMessage is NULL, HttpStatus=" + status);
				}

				// OAuth 토큰 재요청 코드 확인
				if (needReissue) {
					if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
						logger.debug("HttpClientAdapterServiceRest] retry access token response code = ["
								+ vo.getResponseType() + "] message = [" + new String(responseMessage, vo.getEncode())
								+ "]");
					}

					// 토큰 재발급
					AccessTokenManager tokenManager = AccessTokenManager.getInstance();
					String oldToken = accessToken == null ? null : accessToken.getAccessToken();
					OAuth2AccessTokenVO newaccessToken = (OAuth2AccessTokenVO) tokenManager
							.retryAccessTokenVO(vo.getAdapterGroupName(), prop, oldToken);
					
					setAuthHeaders(method, accessToken, authorizationHeaderName);

					if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
						logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName()
								+ ") RETRY TOKEN = [" + newaccessToken + "]");
					}

					// executor 생성 (mclient, timeout은 기존 설정 그대로)
					DeadlineAwareRetryExecutor executor =
					    new DeadlineAwareRetryExecutor((CloseableHttpClient)mclient,
					                                   vo.getConnectionTimeout(),
					                                   vo.getTimeout());

					// Properties에서 RetryPolicy 로드
					RetryPolicy policy = RetryPolicy.from(prop); // 설정 로드 방식에 맞게
					
					try (CloseableHttpResponse response = (CloseableHttpResponse) executor.execute(method, context, policy)) {
//					try (CloseableHttpResponse response = (CloseableHttpResponse) mclient.execute(method)) {
						status = response.getCode();
						responseMessage = EntityUtils.toByteArray(response.getEntity());
						logger.debug("[responseMessageOri 바이트 배열 길이 ]" + responseMessage.length);

//						responseMessage = doOutboundPostFilter(responseMessageOri, encryptAlgorithm, vo.getAdapterName(), accessToken); // jwhong
						
						responseHeaders = response.getHeaders();
						Header headerContentType = response.getHeader("Content-Type");
						if(headerContentType != null) {
							responseContentType = headerContentType.getValue();
						}
						
						if(responseContentType == null)
							responseContentType = ContentType.APPLICATION_JSON.getMimeType();
						
						tempProp.setProperty("RES_CONTENT_TYPE", responseContentType);
						
						TxFileLogger.logTxFile(tempProp, new String(responseMessage,  vo.getEncode()), "[OUT_RECV]");

						if (logger.isDebug()) {
							logger.debug("[received status]" + status);
							logger.debug("HttpClientAdapterServiceRest] RECV (" + vo.getAdapterGroupName() + ") = [" + new String(responseMessage, vo.getEncode()) + "]");
						}
					}catch (IOException e){
						throw new Exception("retry excuteMethod Exceptioin = " + e.getMessage());
					}


					if (status == 302) {
						if (!StringUtils.contains(relayResponseHeaderKeys, "Location")) {
							relayResponseHeaderKeys += ",Location";
						}
					} else {
						String errMsg = String.format(
								"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s  response Data=%s",
								status, vo.getAdapterGroupName(), vo.getAdapterName(), uri, rmethod, responseMessage);
						throw new Exception(errMsg);
					}

					// ----------------------------------------------------------
					if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
						logger.debug("HttpClientAdapterServiceRest] RETRY responseType =" + vo.getResponseType());
						logger.debug("HttpClientAdapterServiceRest] RETRY RECV " + vo.getEncode() + "("
								+ vo.getAdapterGroupName() + ") = [" + new String(responseMessage, vo.getEncode())
								+ "]");
						logger.debug("HttpClientAdapterServiceRest] RETRY RECV (" + vo.getAdapterGroupName() + ") = "
								+ CommonLib.getDumpMessage(responseMessage));
					}
					// ----------------------------------------------------------
				}
			}

			if (vo.getTraceLevel() >= 3) {
				HttpMemoryLogger.txlog(vo.getAdapterGroupName() + vo.getAdapterName(),
						"RECV [" + new String(responseMessage, vo.getEncode()) + "]"
								+ CommonLib.getDumpMessage(responseMessage));
			}
			
			String jsonStr = new String(responseMessage, vo.getEncode());
			
			if ( jsonStr.trim().startsWith("[") ) {
				jsonStr = DJB_ROOTLESS_ARRAY + jsonStr + "}";
				responseMessage = jsonStr.getBytes(vo.getEncode());
			}
			
			Properties responseHeaderProp = assignRelayDataToInbound(tempProp, responseHeaders);
			assignOutboundPropertyMap(tempProp, status, responseString, responseHeaderProp);
			
			return assignResponseHeaders(method, responseMessage, headerGroupName, vo.getEncode(), responseContentType, 
					relayResponseHeaderKeys, status, responseHeaderProp);
		} catch (SocketTimeoutException ste) { // Read Timeout :: HttpClient 3.1일 경우
			if (vo.getTraceLevel() >= 3) {
				HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
						"HttpClientAdapterServiceRest] SocketTimeoutException (" + vo.getAdapterGroupName() + ") : "
								+ ste.toString(),
						ste);
			}
			logger.error("HttpClientAdapterServiceRest] SocketTimeoutException (" + vo.getAdapterGroupName() + ") : "
					+ ste.toString(), ste);
			throw ste;
		} catch (ConnectException ce) {
			if (vo.getTraceLevel() >= 3) {
				HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
						"HttpClientAdapterServiceRest] Connection Exception (" + vo.getAdapterGroupName() + ") : "
								+ ce.toString(),
						ce);
			}
			logger.error("HttpClientAdapterServiceRest] Connection Exception (" + vo.getAdapterGroupName() + ") : "
					+ ce.toString(), ce);
			throw ce;
		} catch (Exception e) {
			if (vo.getTraceLevel() >= 3) {
				HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(), e.toString(), e);
			}
			logger.error("HttpClientAdapterServiceRest] Exception (" + vo.getAdapterGroupName() + ") : " + e.toString(),
					e);
			
			Properties responseHeaderProp = assignRelayDataToInbound(tempProp, responseHeaders);
			assignOutboundPropertyMap(tempProp, status, responseString, responseHeaderProp);
			
			throw e;
		} finally {
			if (status != HttpStatus.SC_OK) {
				String[] msgArgs = new String[1];
				msgArgs[0] = String.valueOf(status);
				String resMsg = ExceptionUtil.make("RDCEAIAHA013", msgArgs);
				if (logger.isDebug()) {
					logger.debug(resMsg);
				}
			}
		}
	}

	private void assignOutboundPropertyMap(Properties tempProp, int status, String responseString,
			Properties responseHeaderProp) {
		Map<String, Object> map = new HashMap<String, Object>();
		tempProp.put(HttpAdapterServiceKey.OUTBOUND_PROPERTY_MAP, map);
		map.put(HttpAdapterServiceKey.OUTBOUND_RESPONSE_HEADERS, responseHeaderProp);
		map.put(HttpAdapterServiceKey.OUTBOUND_RESPONSE_MESSAGE, responseString);
		map.put(HttpAdapterServiceKey.OUTBOUND_RESPONSE_STATUS, status);
	}

	private Properties assignRelayDataToInbound(Properties prop, Header[] responseHeaders) {
		Properties headerProp = new Properties();
		if (responseHeaders == null || responseHeaders.length == 0) {
			return headerProp;
		}

		for (Header header : responseHeaders) {
			headerProp.put(header.getName(), header.getValue());
		}

		return headerProp;
	}

	/**
	 * 현재 1단계 레이아웃에만 적용되도록 구현됨.
	 *
	 * @param method
	 * @param responseMessage
	 * @param headerGroupName
	 * @param encode
	 * @param messageType
	 * @param relayHeaderKeys
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	private Object assignResponseHeaders(HttpUriRequestBase method, byte[] responseMessage, String headerGroupName,
										 String encode, String responseContentType, String relayHeaderKeys, int status, Properties responseHeaderProp) throws Exception {
		String messageType = MessageType.JSON;
		if (StringUtils.startsWith(responseContentType, ContentType.APPLICATION_XML.getMimeType())) {
			logger.debug("Content-Type xml received.");
			messageType = MessageType.XML;
		} else if (StringUtils.startsWith(responseContentType, ContentType.APPLICATION_JSON.getMimeType())) {
			logger.debug("Content-Type json received.");
			messageType = MessageType.JSON;
		} else {
			messageType = "ETC";
		}
		
		// charset 추출, 없으면 파라미터 encdoe 이용
		ContentType oContentType = ContentType.parse(responseContentType);
		Charset contentTypeCharset = oContentType.getCharset();
		String charset = encode;
		if (contentTypeCharset != null)
			charset = contentTypeCharset.displayName();

		if (!StringUtils.equalsAny(messageType, MessageType.JSON, MessageType.XML) || StringUtils.isBlank(headerGroupName)
				|| StringUtils.isBlank(relayHeaderKeys)) {
			return new String(responseMessage, charset);
		}

		if(StringUtils.equalsAny(messageType, MessageType.JSON)) {
			JSONObject headerJson = new JSONObject();
			if (StringUtils.equalsIgnoreCase(relayHeaderKeys, "ALL")) {
				for (Enumeration<Object> e = responseHeaderProp.keys(); e.hasMoreElements(); ) {
					String key = (String)e.nextElement();
					headerJson.put(StringUtils.lowerCase(key), responseHeaderProp.getProperty(key));
				}
			} else {
				String[] relayKeyArr = org.springframework.util.StringUtils.tokenizeToStringArray(relayHeaderKeys, ",");
				for (String key : relayKeyArr) {
					String value = responseHeaderProp.getProperty(key);
					if (StringUtils.isNotBlank(value)) {
						headerJson.put(StringUtils.lowerCase(key), value);
					}
				}
			}
	
			headerJson.put(HTTP_STATUS, String.valueOf(status));
	
			if (headerJson.size() <= 0) {
				return new String(responseMessage, charset);
			}
	
			JSONObject message = null;
			if (responseMessage == null || responseMessage.length == 0) {
				message = new JSONObject();
			} else {
				message = parseJson(new String(responseMessage, charset));
				if (message == null) {
					message = new JSONObject();
					message.put("Malformed_Response_Message", new String(responseMessage, charset));
				}
			}
	
			if (StringUtils.isNotBlank(headerGroupName) && message != null)
				message.put(headerGroupName, headerJson);
			
			return message;
		} else if (StringUtils.equalsAny(messageType, MessageType.XML)) {
			Document doc = XMLUtils.convertXmlDocument(new String(responseMessage, charset));
			Element root = doc.getRootElement();
			Element headerGroupEle = root.addElement(headerGroupName);
			if (StringUtils.equalsIgnoreCase(relayHeaderKeys, "ALL")) {
				for (Enumeration<Object> e = responseHeaderProp.keys(); e.hasMoreElements(); ) {
			        String key = (String)e.nextElement();
			        headerGroupEle.addElement(StringUtils.lowerCase(key)).setText(responseHeaderProp.getProperty(key));
			    }
			} else {
				String[] relayKeyArr = org.springframework.util.StringUtils.tokenizeToStringArray(relayHeaderKeys, ",");
				for (String key : relayKeyArr) {
			    	String value = responseHeaderProp.getProperty(key);
					if (StringUtils.isNotBlank(value)) {
						 headerGroupEle.addElement(StringUtils.lowerCase(key)).setText(value);
					}
				}
			}
			return doc.asXML();
		} else {
			return new String(responseMessage, charset);
		}
	}

	protected void setAuthHeaders(HttpUriRequestBase method, String authorization) throws Exception {
		method.setHeader("Authorization",
				String.format("%s", authorization));
	}

	protected void setAuthHeaders(HttpUriRequestBase method, String authorization, String authorizationHeaderName) throws Exception {
		method.setHeader(authorizationHeaderName,
				String.format("%s", authorization));
	}

	protected void setAuthHeaders(HttpUriRequestBase method, OAuth2AccessTokenVO accessToken) throws Exception {
		method.setHeader("Authorization",
				String.format("%s %s", AccessTokenVO.BEARER_TYPE, accessToken.getAccessToken()));
	}
	
	protected void setAuthHeaders(HttpUriRequestBase method, OAuth2AccessTokenVO accessToken, String authorizationHeaderName) throws Exception {
		method.setHeader(authorizationHeaderName,
				String.format("%s %s", AccessTokenVO.BEARER_TYPE, accessToken.getAccessToken()));
	}

	/* nice on 나이스 지키미 용으로 생성함
	 * jwhong  2015-11-04
	 */
	private void setNiceOnAuthHeaders(HttpUriRequestBase method, String auth) throws Exception {
		method.setHeader("Authorization",
				String.format("%s %s", "bearer", auth));  // 나이스지키미 format임, bearer을 소문자로 보내야함
		String productId = PropManager.getInstance().getProperty("NiceOnProperty","productId.value");
		method.setHeader("ProductID", productId);
		//method.setHeader("Authorization",
		//		String.format("%s %s", AccessTokenVO.BEARER_TYPE, accessToken.getAccessToken()));
	}

	/* nice clientid 추출을 위하여 추가한 내용임. jwhong
	 *
	 */
	private String JwtClientIdExtractor(String inboundToken) {

		String tokenClientId ="";
		try {
			SignedJWT signedJWT = SignedJWT.parse(inboundToken);
			tokenClientId = (String) signedJWT.getJWTClaimsSet().getClaim(PAYLOAD_PARAM_NAME_CLIENT_ID);
		} catch (Exception e) {
			logger.error(e.getMessage());
			tokenClientId = "";
		}

		logger.debug("[ NICE Token Client ID ]" + tokenClientId);
		return tokenClientId;

	}


	private boolean checkTokenRetry(byte[] responseMessage, String tokenErrorCodeKey, String tokenErrorCodeValues,
									String encode) {
		if (responseMessage == null) {
			return false;
		}

		if (StringUtils.isBlank(tokenErrorCodeKey)) {
			return false;
		}

		if (StringUtils.isBlank(tokenErrorCodeValues)) {
			return false;
		}

		try {
			DocumentContext jsonContext = JsonPath.parse(new String(responseMessage, encode));
			String responseCode = jsonContext.read(tokenErrorCodeKey);
			if (StringUtils.isBlank(responseCode)) {
				return false;
			}

			String[] arr = org.springframework.util.StringUtils.tokenizeToStringArray(tokenErrorCodeValues, ",");
			return ArrayUtils.contains(arr, responseCode);
		} catch (Exception e) {
			logger.error("HttpClientAdapterServiceRest] checkTokenRetry error=" + e.getMessage());
		}

		return false;
	}

	protected void assignRequestHeaders(HttpUriRequestBase method, Object httpHeader, Properties prop) {
		if (httpHeader != null) {
			if (httpHeader instanceof JSONObject) {
				JSONObject jsonObject = (JSONObject) httpHeader;
				for (Object key : jsonObject.keySet()) {
					Object obj = jsonObject.get(key);
					if ((obj instanceof JSONObject) || (obj instanceof JSONArray)) {
						continue;
					}

					method.setHeader((String) key, (String) obj);

					if (logger.isDebugEnabled()) {
						logger.debug("Request Header :" + (String) key + "=[" + (String) obj + "]");
					}

				}
			}
		}
		//전문에서 추출한 httpHeader값 외 어댑터에서 최종적으로 적용되도록,
		String httpSettingJsonStr = prop.getProperty( HTTP_HEADER_SETTING );
		
		if( StringUtils.isBlank(httpSettingJsonStr) )
		{
			if( logger.isInfoEnabled() ) {
				logger.info("HTTP_HEADER_SETTING value is not JSONObject Type, skip.");
			}
				
			return;
		}
		
		try {
			JSONObject httpValues = (JSONObject) JSONValue.parse(httpSettingJsonStr);
			
			for (Object key : httpValues.keySet()) {
				Object obj = httpValues.get(key);
				if ((obj instanceof JSONObject) || (obj instanceof JSONArray)) {
					continue;
				}
				
				method.setHeader((String) key, obj);
				
				if (logger.isDebugEnabled()) {
					logger.debug("Request Header :" + (String) key + "=[" + (String) obj + "]");
				}

			}
			
		}catch (Exception e) {
			logger.error("HTTP_HEADER_SETTING value is not JSONObject Type, skip.", e);
		}
			
	}
	
	protected void assignFilterHeaders(HttpUriRequestBase method, Properties tempProp) {
		try {
			Properties filterHeaders = (Properties)tempProp.get("FILTERHEADER");
			if (filterHeaders != null){
				for (Entry<Object, Object> e : filterHeaders.entrySet()) {
					String key = (String) e.getKey();
					String value = (String) e.getValue();
					method.setHeader(key, value);
	
					if (logger.isDebugEnabled()) {
						logger.debug("OutBound Filter] Request Header :" + key + "=[" + value + "]");
					}
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
	}

	/*
	 * KJBank Target System으로 요청 보낼때 header에 clientId(업체정보), APIM거래추적자(UUID), 최초 요청시간, guid 추가해서 보낸다. jwhong
	 * token 만  return 하는것으로 수정함
	 */
	private String assignRequestKJHeaders(HttpUriRequestBase method, Properties prop, Properties tempProp){

		//weblogic 에서는 tempProp.get 이 property로 return 해어 아래처럼 수정함. ClassCastException 발생함.
		//Properties inboundHeaders = (Properties) tempProp.get(HttpAdapterServiceKey.INBOUND_HEADER);
		Properties inboundHeaders = null;
		String authorization ="";
		try {
			Object headerObj = tempProp.get(HttpAdapterServiceKey.INBOUND_HEADER);
			if (headerObj instanceof Properties) {    //tomcat
				inboundHeaders = (Properties) headerObj;
				for ( String k : inboundHeaders.stringPropertyNames()) {
					if(k.equalsIgnoreCase("authorization")) {
						authorization = inboundHeaders.getProperty(k);
						break;
					}
				}
			} else if (headerObj instanceof String) {  //weblogic
				String str = (String) headerObj;
				str = str.substring(1, str.length() - 1);
				// 2. key=value 쌍 분리
				String[] entries = str.split(",");
				// map에 담기
				Map<String, String> map = new HashMap<>();
				for (String entry : entries) {
				    String[] kv = entry.split("=", 2);
				    if (kv.length == 2) {
				        map.put(kv[0].trim(), kv[1].trim());
				    }
				}
				for (String k : map.keySet()) {
				    if (k.equalsIgnoreCase("authorization")) {
				    	authorization = map.get(k);
				        break;
				    }
				}
			}	
		} catch (Exception  e) {
		    e.printStackTrace();
		}
		
		String jwtToken = "";
		
		if (authorization != null && authorization.startsWith("Bearer ")) {
		    jwtToken = authorization.substring(7); // "Bearer " 이후의 JWT만 추출
		}
        
        return jwtToken;
	}
	
    private static Map<String, String> parseInboundHeader(String str) {
        java.util.HashMap<String, String> map = new java.util.HashMap<>();
        if (str == null || str.isEmpty()) return map;

        // 중괄호 제거
        str = str.trim();
        if (str.startsWith("{") && str.endsWith("}")) {
            str = str.substring(1, str.length() - 1);
        }

        // key=value 쌍 분리
        String[] pairs = str.split(",");
        for (String pair : pairs) {
            String[] kv = pair.split("=", 2);
            if (kv.length == 2) {
                map.put(kv[0].trim(), kv[1].trim());
            }
        }
        return map;
    }

	protected String assignPostBody(Object eaiBody, String mimeType, String charset, HttpUriRequestBase method,
			boolean chunked) throws Exception {
		if (eaiBody == null) {
			return "";
		}
		
		if (eaiBody instanceof JSONObject) {
			JSONObject jsonObject = (JSONObject) eaiBody;
			if( jsonObject.containsKey("DJB_ROOTLESS_ARRAY") ) {
				eaiBody = jsonObject.get("DJB_ROOTLESS_ARRAY");
			}
		}

		if (StringUtils.contains(mimeType, "application/x-www-form-urlencoded")) {
			List<NameValuePair> params = new ArrayList<>();
			if (eaiBody instanceof JSONObject) {
				JSONObject jsonObject = (JSONObject) eaiBody;
				for (Object key : jsonObject.keySet()) {
					params.add(new BasicNameValuePair((String) key, (String) jsonObject.get(key)));
				}
			} else if (eaiBody instanceof Document) {
				Document bodyDoc = (Document) eaiBody;
				Element root = bodyDoc.getRootElement();
				List<Element> childrenEle = XMLUtils.getChilds(root);
				for (Element child : childrenEle) {
					params.add(new BasicNameValuePair(child.getName(), child.getText()));
				}
			}
			ContentType contentTypeObj = ContentType.create(mimeType, charset);
			CustomUrlEncodedFormEntity entity = new CustomUrlEncodedFormEntity(params, contentTypeObj.getCharset(), chunked);
			method.setEntity(entity);
			return params.toString();
		} else {
			ContentType contentTypeObj = ContentType.create(mimeType, charset);

			// 요청 본문을 StringEntity 객체로 생성
			String body = "";
			if (eaiBody instanceof Document) {
				body = ((Document)eaiBody).asXML();
			} else if(eaiBody instanceof JSONObject) {
				body = ((JSONObject)eaiBody).toJSONString();
			} else {
				body = eaiBody.toString();
			}
			StringEntity entity = new StringEntity(body, contentTypeObj, chunked);

			// 요청에 본문 추가
			method.setEntity(entity);
			return body;
//			ContentType contentTypeObj = ContentType.create(contentType, charset);
//
//			String eaiBodyMessage = doOutboundPreFilter(eaiBody, adapterName, niceAuth, inboundToken, currentDate); // jwhong
//			StringEntity entity = new StringEntity(eaiBodyMessage, contentTypeObj);
//			// 요청 본문을 StringEntity 객체로 생성
//			//StringEntity entity = new StringEntity(eaiBody.toString(), contentTypeObj);
//
//			// 요청에 본문 추가
//			method.setEntity(entity);
		}
	}

	// from here by jwhong
	private String doOutboundPreFilter(Object eaiBody, String adapterName, String niceAuth, String inboundToken, Date currentDate) throws Exception {

		Properties properties = AdapterPropManager.getInstance().getProperties(adapterName); // jwhong
		String encryptAlgorithm = properties.getProperty("ENCRYPT_ALGORITHM","");   // jwhong
		String encryptBaseKeyType = properties.getProperty("ENCRYPT_BASE_TYPE");
		String encryptClientId = properties.getProperty("ENCRYPT_CLIENT_ID");
		String encryptAES256Iv = properties.getProperty("ENCRYPT_AES256_IV");
		String encryptAES256Key = properties.getProperty("ENCRYPT_AES256_KEY");
		String certPath = properties.getProperty("ENCRYPT_CERT_PATH");

		// outbound encrypt 는 SecretKey 또는 NICE-auth 가 암호화 key로 사용된다.
		// outbound 알림결과는 SecretKey, NICE-auth, Token을 사용한다.
		// 참고로 inbound encrypt 에는 Token 또는 SecretKey 가 암호화 key로 사용된다.
		// 여기에 NICE-auth logic 추가함 .
		String clientSecret = "";
		if ("TOKEN".equalsIgnoreCase(encryptBaseKeyType)) {
			clientSecret  = inboundToken;
		} else if ( "SECRETKEY".equalsIgnoreCase(encryptBaseKeyType)) {
			OAuth2Manager manager = OAuth2Manager.getInstance();
			ClientDetails clientDetail = manager.getClientDeatilsStore().get(encryptClientId);
			if ( clientDetail != null ) {   // not null 이라는 것은 APIM Oauth Server에 등록된 client ID 이다.
				// 업체가 우리 OAuth 를 사용하는 경우임
				clientSecret = clientDetail.getClientSecret();
			}  else {  // 이경우는 우리 OAuth를 사용안하는 경우임, 업체에서 사용하는 secretkey를 사용한다.
				clientSecret = encryptClientId;
			}
		}

		// Nice-auth ,  token 값을 substring 해서 사용한다. 나이스 지키미는 adapter token에서 추출된 token을 사용한다.
		if  (useAdapterToken && "AES256-NICEON".equals(encryptAlgorithm)) {
			clientSecret = niceAuth;
		}

		// 여기서 SECRETY인지 nice-auth 인지 check 하여 clientSecret 값을 정하는 logic 추가하여 넘겨야한다.

		String responseMessage = doOutboundPreEncrypt(eaiBody, encryptAlgorithm, clientSecret, encryptAES256Iv, encryptAES256Key, certPath, currentDate);
		logger.info("outbound pre encrypte value is :"+responseMessage);
		return responseMessage;

	}
	private String doOutboundPreEncrypt(Object eaiBody, String encryptAlgorithm, String clientSecretKey, String encryptAES256Iv, String encryptAES256Key, String certPath, Date currentDate) throws Exception {

		String encryptedMessage = "";
		String encryptedJsonKey = "";

		encryptedJsonKey = getJsonKey(encryptAlgorithm);

		switch (encryptAlgorithm) {
			case "AES":
				encryptedMessage = encrypt(eaiBody.toString()); // encrypt by jwhong
				break;
			case "AES128":
			case "AES128-TOSS":
				try {
					String key = clientSecretKey.substring(22,38);
					encryptedMessage = AESCipher.encrypt(eaiBody.toString(), key);
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("HttpClientAdapterServiceRest] AES128 Encryption error=" + e.getMessage());
					throw new Exception("[HttpClient5AdapterServiceRest] Pre Encrypt Error : Encrypted Error, AES128 Key Invalid");
				}
				break;
			case "AES128-TOGETHER":
				try {
					String key = clientSecretKey.substring(44,60);
					encryptedMessage = AESCipher.encrypt(eaiBody.toString(), key);
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("HttpClientAdapterServiceRest] AES128 Encryption error=" + e.getMessage());
					throw new Exception("[HttpClient5AdapterServiceRest] Pre Encrypt Error : Encrypted Error, AES128 Key Invalid");
				}
				break;
			case "AES256":
				try {
					String key = clientSecretKey.substring(10,42);
					encryptedMessage = AES256Cipher.encrypt(eaiBody.toString(), key);
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("HttpClientAdapterServiceRest] AES256 Encryption error=" + e.getMessage());
					throw new Exception("[HttpClient5AdapterServiceRest] Pre Encrypt Error : Encrypted Error, AES256 Key Invalid");
				}
				break;
			case "AES256-KAKAO":
				try {
					encryptedMessage = AES256Cipher.encrypt(eaiBody.toString(), encryptAES256Iv, encryptAES256Key);
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("HttpClientAdapterServiceRest] AES256 Encryption error=" + e.getMessage());
					throw new Exception("[HttpClient5AdapterServiceRest] Pre Encrypt Error : Encrypted Error, AES256 Key Invalid");
				}
				break;
			case "AES256-TOSS":
				try {
					encryptedMessage = AES256Cipher.encrypt(eaiBody.toString(), encryptAES256Iv, encryptAES256Key);
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("HttpClientAdapterServiceRest] AES256 Encryption error=" + e.getMessage());
					throw new Exception("[HttpClient5AdapterServiceRest] Pre Encrypt Error : Encrypted Error, AES256 Key Invalid");
				}
				break;
			case "AES256-NICEON":
				try {
				    String key = clientSecretKey.substring(10,42);
				    logger.debug("HttpClientAdapterServiceRest] NICE ON AES256 Encryption key is :+="+key);
					encryptedMessage = AES256Cipher.encrypt(eaiBody.toString(), key);
					//encryptedMessage = ExchangeCrypto.encodedData(eaiStringBody, clientSecretKey);
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("HttpClientAdapterServiceRest] AES256 Encryption error=" + e.getMessage());
					throw new Exception("[HttpClient5AdapterServiceRest] Pre Encrypt Error : Encrypted Error, AES256 Key Invalid");
				}
				break;
			case "AES256GCM":
				try {
					byte[] key = AES256GCMCipher.generateKey();
					AES256GCMCipher cipher = new AES256GCMCipher(key);
					byte[] aad = "metadata".getBytes();

					encryptedMessage = cipher.encrypt(eaiBody.toString(), aad);
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("HttpClientAdapterServiceRest] AES256GCM Encryption error=" + e.getMessage());
					throw new Exception("[HttpClient5AdapterServiceRest] Pre Encrypt Error : Encrypted Error, AES256GCM Key Invalid");
				}
				break;
			case "ECDHESA256":
				try {
					ECDHESA256Cipher cipher = new ECDHESA256Cipher();

					encryptedMessage = cipher.encrypt(eaiBody.toString());
					// System.out.println("Encrypted JWE: " + encryptedMessage);

					String decrypted = cipher.decrypt(encryptedMessage);
					// System.out.println("Decrypted Payload: " + decrypted);

					//아래 인증서로 테스트
					ECDHESA256Cipher cipherCert = new ECDHESA256Cipher(certPath);
					encryptedMessage = cipherCert.encrypt(eaiBody.toString());

					decrypted = cipherCert.decrypt(encryptedMessage);

				} catch (Exception e) {
					e.printStackTrace();
					logger.error("HttpClientAdapterServiceRest] AES256GCM Encryption error=" + e.getMessage());
					throw new Exception("[HttpClient5AdapterServiceRest] Pre Encrypt Error : Encrypted Error, ECDHESA256 Key Invalid");
				}
				break;
			default:
				encryptedMessage = eaiBody.toString();
				return encryptedMessage;
			//break;
		}

		if (encryptAlgorithm.equals("AES256-NICEON")) {
			String goodsCls = PropManager.getInstance().getProperty("NiceOnProperty","goods.cls.value");
			Map<String, Object> map = new HashMap<>();
			SimpleDateFormat sdfDateTime =new SimpleDateFormat("yyyyMMddHHmmss");
			map.put("req_dtm", sdfDateTime.format(currentDate)); 
			map.put("goods_cls", goodsCls);
			map.put(encryptedJsonKey, encryptedMessage);
			JSONObject dataBody = new JSONObject();
			dataBody.putAll(map);
			
			JSONObject json = new JSONObject();
			json.put("dataBody", dataBody);
			return json.toJSONString();
		} else {
			Map<String, Object> map = new HashMap<>();
			map.put(encryptedJsonKey, encryptedMessage);
			JSONObject json = new JSONObject();
			json.putAll(map);
			return json.toJSONString();
		}

		//return encryptedMessage;
	}


	private byte[] doOutboundPostFilter(byte[] eaiBody, String decryptAlgorithm, String adapterName, OAuth2AccessTokenVO niceAccessToken ) {

		if ( !encryptResponseApply)  {
			return eaiBody;
		}

		Properties properties = AdapterPropManager.getInstance().getProperties(adapterName); // jwhong
		//String encryptAlgorithm = properties.getProperty("ENCRYPT_ALGORITHM");   // jwhong
		//String encryptBaseKeyType = properties.getProperty("ENCRYPT_BASE_TYPE");
		String encryptClientId = properties.getProperty("ENCRYPT_CLIENT_ID");
		String encryptAES256Iv = properties.getProperty("ENCRYPT_AES256_IV");
		String encryptAES256Key = properties.getProperty("ENCRYPT_AES256_KEY");

		// outbound encrypt 는 SecretKey 또는 NICE-auth 가 암호화 key로 사용된다.
		OAuth2Manager manager = OAuth2Manager.getInstance();
		ClientDetails clientDetail = manager.getClientDeatilsStore().get(encryptClientId);
		String clientSecret = "";
		if ( clientDetail != null ) {
			clientSecret = clientDetail.getClientSecret();
		} else {
			clientSecret = encryptClientId;
		}

		// Nice-auth ,  token 값을 substring 해서 사용한다. 나이스 지키미는 adapter token에서 추출된 token을 사용한다.
		if  (useAdapterToken && "AES256-NICEON".equals(decryptAlgorithm)) {
			clientSecret = niceAccessToken.getAccessToken();
		}

		byte[] resPostMessage = doOutboundPostDecrypt(eaiBody, decryptAlgorithm, clientSecret, encryptAES256Iv, encryptAES256Key);
		return resPostMessage;
	}

	private byte[] doOutboundPostDecrypt(byte[] eaiBody, String decryptAlgorithm, String clientSecretKey, String encryptAES256Iv, String encryptAES256Key ) {

		byte[] decryptedMessage = null;
		String eaiStringBody = new String(eaiBody, StandardCharsets.UTF_8);

		try {
			eaiStringBody = extractBodyMsg(decryptAlgorithm, eaiStringBody);
		} catch (ParseException e) {
			logger.debug("[JSON 파싱 오류 발생 : ]" +e.getMessage());
			return eaiBody;
		}

		//test source
		/*
		logger.debug("eaiBody 바이트 배열 길이: " + eaiBody.length);
		logger.debug("Base64 문자열: " + eaiStringBody);
		logger.debug("Base64 문자열 길이: " + eaiStringBody.length());
		logger.debug("Base64 문자열 끝: " + eaiStringBody.substring(eaiStringBody.length() - 10));
		*/

		// Base64 디코딩 테스트
		try {
			byte[] decoded = Base64.getDecoder().decode(eaiStringBody);
			logger.debug("[디코딩 성공, 길이: ]" + decoded.length);
		} catch (IllegalArgumentException e) {
			logger.debug("[Base64 디코딩 실패: ]" + e.getMessage());
		}
		// end test source

		switch (decryptAlgorithm) {
			case "AES":
				decryptedMessage = decrypt(eaiBody); // encrypt by jwhong
				break;
			case "AES128":
			case "AES128-TOSS":
				try {
					String key128 = clientSecretKey.substring(22,38);
					String decryptedStrMessage = AESCipher.decryptExistException(eaiStringBody, key128);
					decryptedMessage =  decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("HttpClientAdapterServiceRest] AES128 Decryption error=" + e.getMessage());
				}
				break;
			case "AES128-TOGETHER":
				try {
					String key128 = clientSecretKey.substring(44,60);
					String decryptedStrMessage = AESCipher.decryptExistException(eaiStringBody, key128);
					decryptedMessage =  decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("HttpClientAdapterServiceRest] AES128 Decryption error=" + e.getMessage());
				}
				break;
			case "AES256":
				try {
					String key = clientSecretKey.substring(10,42);
					String decryptedStrMessage = AES256Cipher.decrypt(eaiStringBody, key);
					decryptedMessage =  decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("HttpClientAdapterServiceRest] AES256 Decryption error=" + e.getMessage());
				}
				break;
			case "AES256-KAKAO":
				try {
					String decryptedStrMessage = AES256Cipher.decrypt(eaiStringBody, encryptAES256Iv, encryptAES256Key);
					decryptedMessage =  decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("HttpClientAdapterServiceRest] AES256 Encryption error=" + e.getMessage());
				}
				break;
			case "AES256-TOSS":
				try {
					String decryptedStrMessage = AES256Cipher.decrypt(eaiStringBody, encryptAES256Iv, encryptAES256Key);
					decryptedMessage =  decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("HttpClientAdapterServiceRest] AES256 Encryption error=" + e.getMessage());
				}
				break;
			case "AES256-NICEON":
				try {				
				    String key = clientSecretKey.substring(10,42);
					String decryptedStrMessage = AES256Cipher.decrypt(eaiStringBody, key);
					decryptedMessage =  decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("HttpClientAdapterServiceRest] AES256 Decryption error=" + e.getMessage());
				}
				break;
			case "AES256GCM":
				try {
					byte[] key = AES256GCMCipher.generateKey();
					AES256GCMCipher cipher = new AES256GCMCipher(key);
					byte[] aad = "metadata".getBytes();
					String decryptedStrMessage = cipher.decrypt(eaiStringBody, aad);
					decryptedMessage =  decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("HttpClientAdapterServiceRest] AES256 Decryption error=" + e.getMessage());
				}
				break;
			default:
				try {
					decryptedMessage = Arrays.copyOf(eaiBody, eaiBody.length);
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("HttpClientAdapterServiceRest] doOutboundPostFilter Array copy error=" + e.getMessage());
				}
				break;
		}

		return decryptedMessage;
	}


	private String extractBodyMsg(String decryptAlgorithm, String eaiStringBody) throws ParseException {

		String decryptedJsonKey = "";
		String decryptedBodyMessage = "";

		decryptedJsonKey = getJsonKey(decryptAlgorithm);

		try {
			JSONParser parser = new JSONParser();
			JSONObject jsonObject = (JSONObject) parser.parse(eaiStringBody);
			decryptedBodyMessage = (String) jsonObject.get(decryptedJsonKey);
		} catch (ParseException e) {
			e.printStackTrace();
			logger.error("HttpClient5AdapterServiceRest] extractBodyMsg error : " + e.getMessage());
			throw e;
		}

		return decryptedBodyMessage;

	}

	private String getJsonKey(String Algorithm) {

		String jsonKey = "";

		switch (Algorithm) {
			case "AES128":
			case "AES128-TOSS":
				jsonKey = "preScreeningRequest";
				break;
			case "AES128-TOGETHER":
				jsonKey = "obpTxData";
				break;
			case "AES256":
				jsonKey = "preScreeningRequest";
				break;
			case "AES256-KAKAO":
				jsonKey = "encrypted_data";
				break;
			case "AES256-TOSS":
				jsonKey = "encryptedData";
				break;
			case "AES256-NICEON":
				jsonKey = "enc_data";
				break;
			case "AES256GCM":
				break;
			default:
				break;
		}
		return jsonKey;
	}
	// by jwhong
	private String encrypt(String plainText) {
		try {
			SecretKeySpec key = new SecretKeySpec("1234567890123456".getBytes(), "AES");
			Cipher cipher = Cipher.getInstance("AES");
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte[] encrypted = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
			return Base64.getEncoder().encodeToString(encrypted);
		} catch (Exception e) {
			// 예외 로그 출력 또는 사용자 정의 처리
			e.printStackTrace();
			return null; // 또는 에러 메시지 반환
		}
	}


	public static byte[] decrypt(byte[] encryptedBytes) {
		try {
			// byte[] --> Base64 문자열로 변환
			String encryptedText = new String(encryptedBytes, StandardCharsets.UTF_8).trim();
			// 암호화에 사용한 키와 동일한 키 사용
			SecretKeySpec key = new SecretKeySpec("1234567890123456".getBytes(), "AES");

			// 암호화와 동일한 알고리즘 설정
			Cipher cipher = Cipher.getInstance("AES");
			cipher.init(Cipher.DECRYPT_MODE, key);

			// Base64로 인코딩된 문자열을 디코딩
			byte[] decodedBytes = Base64.getDecoder().decode(encryptedText);

			// 복호화 수행
			byte[] decryptedBytes = cipher.doFinal(decodedBytes);

			// UTF-8 문자열로 변환하여 반환
			//return new String(decryptedBytes, StandardCharsets.UTF_8);
			//복호화된 바이트 배열 반환
			return decryptedBytes;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}


	private HashMap<String, String> getParameters(Object message) throws Exception {

		HashMap<String, String> result = new HashMap<String, String>();

		if (message != null) {
			if (message instanceof JSONObject) {
				JSONObject jsonObject = (JSONObject) message;
				for (Object key : jsonObject.keySet()) {
					Object obj = jsonObject.get(key);
					if ((obj instanceof JSONObject) || (obj instanceof JSONArray)) {
						continue;
					}
					result.put((String) key, getStringValue(obj));
				}
			} else {
				String[] messages = ((String) message).split("&");
				String[] data = null;

				for (int i = 0; i < messages.length; i++) {
					data = messages[i].split("=", 2);
					if (data.length == 2) {
						result.put(data[0], data[1]);
					}
				}
			}
		}

		return result;
	}

	public String getStringValue(Object obj) {
		if (obj == null) {
			return null;
		}

		if (obj instanceof String) {
			return (String) obj;
		} else if (obj instanceof Long) {
			return Long.toString((Long) obj);
		} else if (obj instanceof BigDecimal) {
			return ((BigDecimal) obj).toPlainString();
		} else {
			return (String) obj;
		}
	}

	public static Object parseJsonGeneric(String jsonData) {
		if (StringUtils.isBlank(jsonData)) {
			return null;
		}

		try {
			JSONParser parser = new JSONParser();
			Object parsedObj = parser.parse(jsonData);
			return parsedObj;
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}

	@SuppressWarnings("deprecation")
	private JSONObject parseJson(String message) throws Exception {
		if (message == null) {
			return null;
		}

		return (JSONObject) JSONValue.parse(message);
	}

	private Document convertXmlDocument(String message) throws Exception {
		SAXReader builder = new SAXReader();
		Document document = builder.read(new StringReader(message));
		return document;
	}

	@SuppressWarnings("deprecation")
	private String changeUrl(String messageType, String url, String restOption, Object sendData, Map<String, String> inboundPathVariables) {
		if ((MessageType.JSON.equals(messageType) || MessageType.XML.equals(messageType))) {
			try {
				if (StringUtils.isBlank(restOption)) {
					return url;
				}
				List<String> urlVariableList = new ArrayList<String>();
				JSONObject restOptionObject = parseJson(restOption);

				if (restOptionObject == null)
					throw new Exception("restOption is NULL");

				String type = (String) restOptionObject.get("type");
				String requestExtraPath = (String) restOptionObject.get("extraPath");
				url = getUrl(url, requestExtraPath);
				if (TYPE_VARIABLE_URL_REQUEST.equals(type)) {
					Pattern p = Pattern.compile("\\{(.*?)\\}");
					Matcher m = p.matcher(requestExtraPath);
					List<String> uriVariables = new ArrayList<>();
					while(m.find()) {
						String fieldName = m.group(1);
						uriVariables.add(fieldName);
					}
					if (MessageType.JSON.equals(messageType)) {
						JsonNode jsonNode = JsonPathUtil.toTree(sendData);
//						JSONObject jsonObject;
//						if (sendData instanceof JSONObject) {
//							jsonObject = (JSONObject) sendData;
//							
//						} else {
//							jsonObject = (JSONObject) JSONValue.parse((String) sendData);
//						}
						for (String urlVaribleId : uriVariables) {
							String uriVariable = JsonPathUtil.getAt(jsonNode, urlVaribleId, "\\.");
//							String uriVariable = null;
//							if( jsonObject != null ) {
//							    uriVariable = (String) jsonObject.get(urlVaribleId);
//							    jsonObject.remove(urlVaribleId);
//							}
							
							if (StringUtils.isBlank(uriVariable) && inboundPathVariables.containsKey(urlVaribleId)) {
								uriVariable = inboundPathVariables.get(urlVaribleId);
							}
							
							urlVariableList.add(uriVariable);
							
						}
					} else if (MessageType.XML.equals(messageType)) {
						Document doc;
						if (sendData instanceof Document) {
							doc = (Document) sendData;
						} else {
							doc = convertXmlDocument((String) sendData);
						}
						for (Object tempObject : uriVariables) {
							String urlVaribleId = (String) tempObject;
							Element element = (Element) doc.selectSingleNode("//" + urlVaribleId);
							urlVariableList.add(element.getText());
							if (doc.getRootElement() == element) {
								doc = null;
							} else {
								element.getParent().remove(element);
							}
						}
					}
					if (urlVariableList.size() > 0) {
						UriComponents uriComponents = UriComponentsBuilder.fromUriString(url).build();
						Object[] urls = urlVariableList.toArray();
						url = uriComponents.expand(urls).toUriString();
						logger.debug("HttpClientAdapterServiceRest] after extand url=[" + url + "] ");
					}
				}
			} catch (Exception e) {
				logger.error("Failed to change url", e);
			}
		}
		return url;
	}

	private String getUrl(String baseUrl, String extraPath) {
		if (StringUtils.isBlank(extraPath)) {
			return baseUrl;
		}

		if (StringUtils.contains(extraPath, "http://") || StringUtils.contains(extraPath, "https://")) {
			return extraPath;
		}

		String targetUrl = baseUrl;
		if (!targetUrl.endsWith("/")) {
			targetUrl += "/";
		}
		if (extraPath.startsWith("/")) {
			targetUrl += extraPath.substring(1);
		} else {
			targetUrl += extraPath;
		}

		logger.debug("HttpClientAdapterServiceRest] after concatenate url=[" + targetUrl + "] ");
		return targetUrl;
	}
	
	
	private boolean isStatusInIgnore(int status, String errIgnore) {
	    if (errIgnore == null || errIgnore.isEmpty()) return false;

	    String[] tokens = errIgnore.split(",");
	    for (String token : tokens) {
	        token = token.trim();
	        if (token.contains("-")) {
	            // 범위 처리
	            String[] range = token.split("-");
	            int start = Integer.parseInt(range[0].trim());
	            int end = Integer.parseInt(range[1].trim());
	            if (status >= start && status <= end) {
	                return true;
	            }
	        } else {
	            // 단일 숫자 처리
	            int code = Integer.parseInt(token);
	            if (status == code) {
	                return true;
	            }
	        }
	    }
	    return false;
	}

}
