package com.eactive.eai.outbound;

import java.net.SocketTimeoutException;
import java.util.Properties;

import com.eactive.eai.common.TransactionContextKeys;
import com.eactive.eai.common.circuitBreaker.CircuitBreakerManager;
import com.eactive.eai.common.circuitBreaker.type.TypedCircuitBreakerManager;
import com.eactive.eai.util.PropertiesUtil;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import io.github.resilience4j.circuitbreaker.CircuitBreaker;

import org.apache.commons.lang3.StringUtils;

import com.eactive.eai.adapter.AdapterGroupVO;
import com.eactive.eai.adapter.AdapterManager;
import com.eactive.eai.adapter.AdapterPropManager;
import com.eactive.eai.adapter.AdapterVO;
import com.eactive.eai.adapter.http.HttpStatusException;
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
import com.eactive.eai.common.EAIKeys;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.header.HeaderAction;
import com.eactive.eai.common.header.HeaderActionFactory;
import com.eactive.eai.common.header.HeaderActionKeys;
import com.eactive.eai.common.logger.Keys;
import com.eactive.eai.common.message.EAIMessage;
import com.eactive.eai.common.message.EAIMessageKeys;
import com.eactive.eai.common.message.MessageType;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.routing.RouteKeys;
import com.eactive.eai.common.server.EAIServerManager;
import com.eactive.eai.common.stdmessage.STDMessageMapper;
import com.eactive.eai.common.util.MessageUtil;
import com.eactive.eai.common.util.StringUtil;
import com.eactive.eai.common.util.TranLogUtil;
import com.eactive.eai.common.worker.Future;
import com.eactive.eai.common.worker.ResponseMap;
import com.eactive.eai.control.HttpSender;
import com.eactive.eai.control.LogSender;
import com.eactive.eai.control.Transform;
import com.eactive.eai.env.ElinkConfig;
import com.eactive.eai.inbound.processor.Processor;
import com.eactive.eai.message.StandardMessage;
import com.eactive.eai.message.manager.StandardMessageManager;
import com.eactive.eai.message.parser.StandardReader;
import com.eactive.eai.util.SimHeaderUtil;
import com.ext.eai.common.stdmessage.STDMessageKeys;

public class HTTPProcess extends DefaultProcess {
	static final long serialVersionUID = 1L;
	protected static final String TIMEOUT_ERROR = "RECEAIOHP003";
	protected static final String STATUS_ERROR = "RECEAIOHP004";

	protected final ObjectMapper objectMapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
	
	public void outboundCtrlCallServiceAsync() throws Exception {
		// 인터페이스에 셋팅된 타임아웃설정
		int iTimeoutValue = getTimeoutCodeToValue();
		this.timeout = iTimeoutValue * 1000;
		this.tempProp.put(INTERFACE_TIME_OUT, "" + this.timeout);
		try {
			this.tempProp.put(HttpClientAdapterServiceKey.LOG_PROCESS_NO, this.logPssSno);
			this.resObject = HttpSender.callService(this.adapterGroupName, this.outboundProp, this.reqObject, this.tempProp);
		} catch (SocketTimeoutException ste) {
			String[] msgArgs = new String[1];
			msgArgs[0] = this.reqEaiMsg.getEAISvcCd();
			String rspErrorCode = TIMEOUT_ERROR;
			String rspErrorMsg = ExceptionUtil.make(ste, rspErrorCode, msgArgs);
			if (logger.isError())
				logger.error(guidLogPrefix + rspErrorMsg, ste);
			this.resEaiMsg.setRspErr(rspErrorCode,rspErrorMsg);
			throw new RuntimeException(rspErrorCode);
		} catch (HttpStatusException hse) {
			String[] msgArgs = new String[2];
			msgArgs[0] = this.reqEaiMsg.getEAISvcCd();
			msgArgs[1] = Integer.toString(hse.getStatus());
			String rspErrorCode = STATUS_ERROR;
			String rspErrorMsg = ExceptionUtil.make(hse, rspErrorCode, msgArgs);
			if (logger.isError())
				logger.error(guidLogPrefix + rspErrorMsg, hse);
			this.resEaiMsg.setRspErr(rspErrorCode,rspErrorMsg);
			throw new RuntimeException(rspErrorCode);
		} catch (Exception e) {
			String[] msgArgs = new String[1];
			msgArgs[0] = this.reqEaiMsg.getEAISvcCd();
			String rspErrorCode = "RECEAIOHP001";
			String rspErrorMsg = ExceptionUtil.make(e, rspErrorCode, msgArgs);
			if (logger.isError())
				logger.error(guidLogPrefix + rspErrorMsg, e);
			this.resEaiMsg.setRspErr(rspErrorCode,rspErrorMsg);
			throw new RuntimeException(rspErrorCode);
		}
	}

	public void outboundCtrlCallService() throws Exception {
		// 인터페이스에 셋팅된 타임아웃설정
		int iTimeoutValue = getTimeoutCodeToValue();
		this.timeout = iTimeoutValue * 1000;
		this.tempProp.put(INTERFACE_TIME_OUT, "" + this.timeout);
		try {
			// API별 이용
			String apiId = reqEaiMsg.getEAISvcCd();
			CircuitBreaker circuitBreaker = TypedCircuitBreakerManager.getInstance().getCircuitBreaker(apiId);
			
			// 디폴트 이용
			if(circuitBreaker == null) {
				String circuitBreakerUseYn = PropManager.getInstance().getProperty("CircuitBreaker", "useYn");
				if ("Y".equals(circuitBreakerUseYn))
					circuitBreaker = CircuitBreakerManager.getInstance().getCircuitBreaker(apiId);
			}
			
			if (circuitBreaker != null) {
				// ObjectMapper 인스턴스 생성
				ObjectMapper objectMapper = new ObjectMapper();
	
				// 서킷 브레이커의 메트릭 정보와 상태 정보를 직접 Node로 변환
				ObjectNode combinedNode = objectMapper.createObjectNode();
				combinedNode.put("state", circuitBreaker.getState().toString());
				combinedNode.set("metrics", objectMapper.valueToTree(circuitBreaker.getMetrics()));
	
				logger.info("CircuitBreaker state " + combinedNode.toString());
				this.resObject = circuitBreaker.executeCallable(() -> HttpSender
					.callService(this.adapterGroupName, this.outboundProp, this.reqObject, this.tempProp));
			} else {
				this.resObject = HttpSender.callService(this.adapterGroupName, this.outboundProp, this.reqObject, this.tempProp);
			}
			// 응답코드에 대한 처리
			this.resEaiMsg = setResponseForOutbound(this.resEaiMsg);
			if (!com.eactive.eai.adapter.Keys.IF_STANDARD.equals(this.adptrMsgPtrnCd)) {
				this.resEaiMsg = setSendTime(this.resEaiMsg);
			}
		} catch (SocketTimeoutException ste) {
			String[] msgArgs = new String[1];
			msgArgs[0] = this.reqEaiMsg.getEAISvcCd();
			String rspErrorCode = TIMEOUT_ERROR;
			String rspErrorMsg = ExceptionUtil.make(ste, rspErrorCode, msgArgs);
			if (logger.isError())
				logger.error(guidLogPrefix + rspErrorMsg, ste);
			this.resEaiMsg.setRspErr(rspErrorCode,rspErrorMsg);
			throw new RuntimeException(rspErrorCode);
		} catch (HttpStatusException hse) {
			String[] msgArgs = new String[2];
			msgArgs[0] = this.reqEaiMsg.getEAISvcCd();
			msgArgs[1] = Integer.toString(hse.getStatus());
			String rspErrorCode = STATUS_ERROR;
			String rspErrorMsg = ExceptionUtil.make(hse, rspErrorCode, msgArgs);
			if (logger.isError())
				logger.error(guidLogPrefix + rspErrorMsg, hse);
			this.resEaiMsg.setRspErr(rspErrorCode,rspErrorMsg);
			throw new RuntimeException(rspErrorCode);
		} catch (Exception e) {
			String[] msgArgs = new String[1];
			msgArgs[0] = this.reqEaiMsg.getEAISvcCd();
			String rspErrorCode = "RECEAIOHP001";
			String rspErrorMsg = ExceptionUtil.make(e, rspErrorCode, msgArgs);
			if (logger.isError())
				logger.error(guidLogPrefix + rspErrorMsg, e);
			this.resEaiMsg.setRspErr(rspErrorCode,rspErrorMsg);
			throw new RuntimeException(rspErrorCode);
		}
	}

	public void logSenderCtrlSendRes() throws Exception {
		try {
			LogSender.send(this.logPssSno, this.resEaiMsg, this.prop);
		} catch (Exception e) {
			String[] msgArgs = new String[1];
			msgArgs[0] = this.resEaiMsg.getEAISvcCd();
			String rspErrorCode = "RECEAIOHP021";
			String rspErrorMsg = ExceptionUtil.make(e, rspErrorCode, msgArgs);
			if (logger.isWarn())
				logger.warn(rspErrorMsg);
		}
	}

	public void logSenderCtrlSendReq() throws Exception {
		try {
			LogSender.send(this.logPssSno, this.reqEaiMsg, this.prop);
		} catch (Exception e) {
			String[] msgArgs = new String[1];
			msgArgs[0] = this.reqEaiMsg.getEAISvcCd();
			String rspErrorCode = "RECEAIOHP021";
			String rspErrorMsg = ExceptionUtil.make(e, rspErrorCode, msgArgs);
			if (logger.isWarn())
				logger.warn(rspErrorMsg);
		}
	}

	public void transControlTransformSingleRes() throws Exception {
		try {
			this.srcTranObject = this.resObject;
			this.tgtTranObject = Transform.transformSingle(this.guidLogPrefix, false, this.diURI,
			this.srcTranObject);
		} catch (Exception e) {
			if (logger.isError())
				logger.error(guidLogPrefix + " 300 변환오류", e);
			String[] msgArgs = new String[1];
			msgArgs[0] = this.reqEaiMsg.getEAISvcCd();
			String rspErrorCode = "RECEAIOHP030";
			String rspErrorMsg = ExceptionUtil.make(e, rspErrorCode, msgArgs);
			if (logger.isError())
				logger.error(guidLogPrefix + rspErrorMsg, e);
			this.resEaiMsg.setRspErr(rspErrorCode,rspErrorMsg);
		}
	}

	public void transControlTransformSingleReq() throws Exception {
		try {
			String bizData = this.reqEaiMsg.getStandardMessage().getBizData();
			if (bizData != null && bizData.length() > 0) {
				this.srcTranObject = bizData;
			}
			this.tgtTranObject = Transform.transformSingle(this.guidLogPrefix, true, this.diURI, this.srcTranObject);
		} catch (Exception e) {
			if (logger.isError())
				logger.error(guidLogPrefix + " 200 변환오류", e);
			String[] msgArgs = new String[1];
			msgArgs[0] = this.reqEaiMsg.getEAISvcCd();
			String rspErrorCode = "RECEAIOHP020";
			String rspErrorMsg = ExceptionUtil.make(e, rspErrorCode, msgArgs);
			if (logger.isError())
				logger.error(guidLogPrefix + rspErrorMsg, e);
			this.resEaiMsg.setRspErr(rspErrorCode,rspErrorMsg);
			throw new Exception(rspErrorMsg);
		}
	}

	public void printCallError(Exception e1) throws Exception {
		this.resObject = new byte[0];

		if (TIMEOUT_ERROR.equals(this.resEaiMsg.getRspErrCd())) {
			if (logger.isDebug()) {
				logger.debug(guidLogPrefix + " UUID[" + this.reqEaiMsg.getSvcOgNo()
						+ "] 수동시스템 Timeout이 발생함 - Adapter 상태 변경하지 않음 ");
			}
		} else if (STATUS_ERROR.equals(this.resEaiMsg.getRspErrCd())) {
			if (logger.isDebug()) {
				logger.debug(guidLogPrefix + " UUID[" + this.reqEaiMsg.getSvcOgNo()
						+ "] 수동시스템 Response status가 200이 아님 - Adapter 상태 변경하지 않음 ");
			}
		} else {
			AdapterManager manager = AdapterManager.getInstance();
			AdapterVO vo = manager.getAdapterVO(this.adapterGroupName, this.adapterName);
			if (vo != null) {
				if (!StringUtils.isEmpty(vo.getTestCallClass())) {
					vo.setStatus(false);
				}
			}
		}
	}

	public void setRcvLogInfo() throws Exception {
		this.logPssSno = TranLogUtil.getResLogSeq(this.svcPssTp, this.svcPssSeq, this.isComp); // 300

		this.prop = new Properties();
		if (this.isSuccess) {
			prop.setProperty(Keys.ERROR_MESSAGE, Keys.FALSE);
		} else {
			prop.setProperty(Keys.ERROR_MESSAGE, Keys.TRUE);
		}
		
		if(MessageUtil.checkRspErrCd(this.resEaiMsg.getRspErrCd())) {
			if (com.eactive.eai.adapter.Keys.IF_STANDARD.equals(this.adptrMsgPtrnCd)) {
				if (logger.isDebug())
					logger.debug(guidLogPrefix + " 내부표준 추출");
				try {
					// 응답전문으로 응답 구조체(resEaiMsg) SET
					resEaiMsg = setRcvLogInfo(resEaiMsg, this.adptrMsgType, this.resObject, this.outboundCharset);
					this.resObject = resEaiMsg.getStandardMessage().getBizDataBytes();
				} catch (Exception e) {
					String[] msgArgs = new String[1];
					msgArgs[0] = this.reqEaiMsg.getEAISvcCd();
					String rspErrorCode = "RECEAIOHP002";
					String rspErrorMsg = ExceptionUtil.make(e, rspErrorCode, msgArgs);
					if (logger.isError())
						logger.error(guidLogPrefix + rspErrorMsg, e);
					this.resEaiMsg.setRspErr(rspErrorCode,rspErrorMsg);
				}
			}
			else if (com.eactive.eai.adapter.Keys.IF_SUBSTANDARD.equals(this.adptrMsgPtrnCd)) {
				if (logger.isDebug())
					logger.debug(guidLogPrefix + "SUB표준 업무데이터 추출");
				try {
					this.resEaiMsg = convertToStandardMessage(resEaiMsg, adptrMsgType, this.resObject, this.outboundCharset);
					this.resObject = resEaiMsg.getStandardMessage().getBizDataBytes();
				} catch (Exception e) {
					e.printStackTrace();
					String[] msgArgs = new String[1];
					msgArgs[0] = this.reqEaiMsg.getEAISvcCd();
					String rspErrorCode = "RECEAIOSP031"; // 잘못된 내부표준메시지 수신[{1}]
					String rspErrorMsg = ExceptionUtil.make(e, rspErrorCode, msgArgs);
					if (logger.isError())
						logger.error(guidLogPrefix + rspErrorMsg, e);
					this.resEaiMsg.setRspErr(rspErrorCode,rspErrorMsg);
				}
			}
		}
		else {
			AdapterManager adapterManager = AdapterManager.getInstance();
			AdapterGroupVO adptGrpVO = adapterManager.getAdapterGroupVO(this.adapterGroupName);
			EAIServerManager eaiServerManager = EAIServerManager.getInstance();
			if (eaiServerManager.isTASEnabledEAIServer()
					&& com.eactive.eai.adapter.Keys.TESTMASTER_TAS.equals(adptGrpVO.getTestMasterYn())) {// 비표준 시뮬레이터
				this.resObject = SimHeaderUtil.getSimData(this.resObject);
			}
		}
	}

	public void setTopicResult() throws Exception {
		try {
			this.jmsRespObject = future.value(this.timeout);
			if (this.jmsRespObject == null) {
				if (logger.isError())
					logger.error(guidLogPrefix + "SYNC-ASYNC - HTTP setTopicResult jmsRespObject is null. timeout="
							+ this.timeout);
				throw new Exception("RECEAIOHP010");
			}
			resEaiMsg = setResponseForOutbound(this.resEaiMsg);
		} catch (Exception e) {
			String[] msgArgs = new String[1];
			msgArgs[0] = this.reqEaiMsg.getEAISvcCd();
			String rspErrorCode = "RECEAIOHP010";
			String rspErrorMsg = ExceptionUtil.make(e, rspErrorCode, msgArgs);
			if (logger.isError())
				logger.error(guidLogPrefix + rspErrorMsg, e);
			this.resEaiMsg.setRspErr(rspErrorCode,rspErrorMsg);
			throw new RuntimeException(rspErrorCode);
		} finally {
			if (jmsRespAction != null) {
				this.jmsRespAction.doEnd();
			}
		}

		if (this.jmsRespObject == null) {
			this.resObject = new byte[0];
		} else if (this.jmsRespObject instanceof EAIMessage) {
			EAIMessage topicEaiMsg = (EAIMessage) this.jmsRespObject;
			this.resObject = topicEaiMsg.getStandardMessage().getBizData();			
		} else if (this.jmsRespObject instanceof byte[]) {
			this.resObject = (byte[]) this.jmsRespObject;
		} else {
			this.resObject = new byte[0];
		}
	}

	public void checkResultMessage() throws Exception {
		if (logger.isDebug()) {
			logger.debug(guidLogPrefix + " SYNC - HTTP RESPONSE MESSAGE : "
					+ MessageUtil.toAdapterTypeString(this.resObject, this.outboundCharset));
		}

	}
	
	public void checkSendResult() throws Exception {
		if (MessageUtil.checkRspErrCd(this.resEaiMsg.getRspErrCd())) {			
			if (logger.isDebug()) {
				logger.debug(guidLogPrefix + " ASYNC - HTTP RESPONSE MESSAGE : "
						+ MessageUtil.toAdapterTypeString(this.resObject, this.outboundCharset));
			}
		}
	}

	public void init() throws Exception {
		this.prop = null;
		
		this.adapterName = this.callProp.getProperty(com.eactive.eai.adapter.Keys.OUT_ADAPTER_NAME);
		
		this.resEaiMsg = this.reqEaiMsg;
		this.tempProp = new Properties();
	      
		// GW 전달 로직 추가
		// tempProp로 넘겨서 하는 이유는 outboundProp가 clone 안하는 로직이라 outboundProp로 넘길시 문제의 소지가 있음
		String transactionId = callProp.getProperty(HttpClientAdapterServiceKey.TRANSACTION_ID);
		String instanceId = callProp.getProperty(HttpClientAdapterServiceKey.INSTANCE_ID);
		if (StringUtils.isNotBlank(transactionId) && StringUtils.isNotBlank(instanceId)) {
			this.tempProp.put(HttpClientAdapterServiceKey.TRANSACTION_ID, transactionId);
			this.tempProp.put(HttpClientAdapterServiceKey.INSTANCE_ID, instanceId);
		}
	      
//		EAIServerManager eaiServerManager = EAIServerManager.getInstance();
//		AdapterManager adapterManager = AdapterManager.getInstance();
//		AdapterGroupVO adptGrpVO = adapterManager.getAdapterGroupVO(reqEaiMsg.getCurrentSvcMsg().getPsvSysItfTp());
//		if (eaiServerManager.isTASEnabledEAIServer() && EAIMessageKeys.TRANTYPE_TAS.equals(reqEaiMsg.getTranType())
//		// RESTAdapter는 교체하지 않는다
//				&& !StringUtils.equals(adptGrpVO.getType(), com.eactive.eai.adapter.Keys.TYPE_REST)) {
//			PropManager manager = PropManager.getInstance();
//			Properties prop = manager.getProperties(RouteKeys.SIM);
//
//			if (reqEaiMsg.getCurrentSvcMsg().isSyncItfTp()) {
//				this.adapterGroupName = prop.getProperty(RouteKeys.SIM_ADAPTER_SYNC, "_SIM_OU_HTT_SyC");
//			} else {
//				this.adapterGroupName = prop.getProperty(RouteKeys.SIM_ADAPTER_ASYNC, "_SIM_OU_HTT_AsC");
//			}
//			this.reqEaiMsg.getSvcMsg(0).setPsvSysItfTp(this.adapterGroupName);
//		} else {
//			this.adapterGroupName = reqEaiMsg.getCurrentSvcMsg().getPsvSysItfTp();
//		}
		
		this.adapterGroupName = reqEaiMsg.getCurrentSvcMsg().getPsvSysItfTp();

		this.svcTsmtUsgTp = this.reqEaiMsg.getSvcTsmtUsgTp(); // Inbound 호출방식
		this.psvItfTp = this.reqEaiMsg.getCurrentSvcMsg().getPsvItfTp(); // 호출방식

		// 복합거래의 보상거래여부를 확인
		this.svcPssTp = this.reqEaiMsg.getSvcPssTp();
		this.svcPssSeq = this.reqEaiMsg.getSvcPssSeq();

		if (this.callProp != null) {
			logger.debug(guidLogPrefix + " COMP_VALUE[" + this.callProp.getProperty(EAIKeys.CALL_COMP_KEY) + "]");
			if (EAIKeys.CALL_COMP_VALUE.equals(this.callProp.getProperty(EAIKeys.CALL_COMP_KEY))) {
				this.isComp = true;
				try {
					this.svcPssSeq = Integer.parseInt(this.callProp.getProperty(EAIKeys.CALL_COMP_SVC_SEQ));
					logger.debug(guidLogPrefix + " CALL_COMP_SVC_SEQ[" + this.svcPssSeq + "]");
				} catch (Exception e) {
					logger.warn(guidLogPrefix + " CALL_COMP_SVC_SEQ Get Error");
				}
			} else {
				this.isComp = false;
			}
		} else {
			this.isComp = false;
		}

		String returnType = getReturnType(reqEaiMsg);

		if (STDMessageKeys.SEND_RECV_CD_RECV.equals(returnType)) {
			this.logPssSno = 400;
		} else {
			this.logPssSno = TranLogUtil.getReqLogSeq(this.svcPssTp, this.svcPssSeq, this.isComp);
		}

		// Inbound Adapter mesageType
		AdapterManager adapterManager = AdapterManager.getInstance();
		AdapterGroupVO inAdptGrpVO = adapterManager.getAdapterGroupVO(this.reqEaiMsg.getSngSysItfTp());
		this.inAdapterMsgType = MessageType.ASC;

		if (inAdptGrpVO == null) {
			if (logger.isWarn()) {
				String tasAdapterName = "";
				if (this.callProp != null)
					tasAdapterName = this.callProp.getProperty(Processor.TAS_ADAPTER_GROUP_NAME);
				logger.warn(guidLogPrefix + "Source Adapter is null, TAS Inbound = " + tasAdapterName);
			}
		} else {
			this.inAdapterMsgType = inAdptGrpVO.getMessageType();
		}
	}

	public String getUrlSubString(String url, int length) {
		try {
			int start = 0;
			if (url.startsWith("http://"))
				start = 7;
			if (url.length() > length + start) {
				url = url.substring(start, length + start);
			} else {
				url = url.substring(start);
			}
		} catch (Exception ex) {
			return "";
		}
		return url;
	}

	public void setSendMsg() throws Exception {
		try {
			// 200 로그를 위한 변환된 메시지부를 설정
			this.reqEaiMsg.getStandardMessage().setBizData(tgtTranObject, this.outboundCharset);
			
			this.reqObject = this.tgtTranObject;
			
			AdapterGroupVO adptGrpVO = null;
			AdapterVO adptVO = null;
			try {
				AdapterManager adapterManager = AdapterManager.getInstance();
				adptGrpVO = adapterManager.getAdapterGroupVO(this.adapterGroupName);

				if (adptGrpVO == null) {
					String msg = String.format("AdapterGroup not found. - groupName %s adapterName %s", adapterGroupName);
					logger.error(msg);
					throw new Exception(msg);
				}
				
				if(StringUtils.isEmpty(this.adapterName)) {
					adptVO = adptGrpVO.nextAdapterVO();
				}
				else {
					adptVO = adptGrpVO.getAdapterVO(adapterName);
				}
				
				if (adptVO == null) {
					String msg = String.format("Adapter not found. - groupName %s adapterName %s", adapterGroupName, adapterName);
					logger.error(msg);
					throw new Exception(msg);
				}
				this.tempProp.setProperty(com.eactive.eai.adapter.Keys.OUT_ADAPTER_NAME, adptVO.getName());
			}
			catch(Exception ex) {
				String[] msgArgs = new String[1];
				msgArgs[0] = String.valueOf(this.adapterGroupName);
				String resMsg = ExceptionUtil.make("RECEAIOHP900", msgArgs);
				throw new Exception(resMsg, ex);
			}
			
			try {
				AdapterPropManager manager = AdapterPropManager.getInstance();
				this.outboundProp = manager.getProperties(adptVO.getPropGroupName());// clone 안함으로 변경
				this.tempProp.setProperty(HttpClientAdapterServiceKey.ADAPTER_GROUP_NAME, this.adapterGroupName);
				this.tempProp.setProperty(HttpClientAdapterServiceKey.ADAPTER_NAME, adptVO.getName());

				// MFC_FAILOVER : FAILOVER = Y 일 경우 무조건 2센터로 라우팅하도록 한다. (2020-08-27)
				PropManager pmanager = PropManager.getInstance();
				String mfcFailOver = pmanager.getProperty("MFC_FAILOVER", "FAILOVER");

				if (mfcFailOver != null && "Y".equals(mfcFailOver.toUpperCase())) {
					String url2grp = this.outboundProp.getProperty(HttpClientAdapterServiceKey.URL_2GRP);
					if (logger.isInfo())
						logger.info(guidLogPrefix + "MFC_FAILOVER URL_2GRP - " + url2grp);
					if (url2grp != null && url2grp.trim().length() > 0) {
						this.tempProp.setProperty(HttpClientAdapterServiceKey.URL, url2grp);
						this.reqEaiMsg.getCurrentSvcMsg().setPsvSysSvcCd(getUrlSubString(url2grp, 20));
					}
					if (logger.isInfo())
						logger.info(guidLogPrefix + "MFC_FAILOVER URL - "
								+ this.tempProp.getProperty(HttpClientAdapterServiceKey.URL));
				} else {
					// 센터구분코드(2) 일 경우, URL_2GRP 로 URL 정보를 치환한다. (2020-07-23)
					// DR일 경우에 대한 처리는 동일하게
//					if (STDMessageKeys.CNTERDSTCD_DR.equals(extmessage.getTargetGroup())) {
//						String url_2grp = this.outboundProp.getProperty(HttpClientAdapterServiceKey.URL_2GRP);
//						if (logger.isInfo())
//							logger.info(guidLogPrefix + "CNTERDSTCD URL_2GRP - " + url_2grp);
//						if (url_2grp != null && url_2grp.trim().length() > 0) {
//							this.tempProp.setProperty(HttpClientAdapterServiceKey.URL, url_2grp);
//							this.reqEaiMsg.getCurrentSvcMsg().setPsvSysSvcCd(getUrlSubString(url_2grp, 20));
//						}
//						if (logger.isInfo())
//							logger.info(guidLogPrefix + "CNTERDSTCD URL - "
//									+ this.tempProp.getProperty(HttpClientAdapterServiceKey.URL));
//					}
				}

				PropertiesUtil.copyPropertyIfPresent(this.callProp, this.tempProp, TransactionContextKeys.TRANSACTION_UUID);

				String svcName = getServiceId(this.reqEaiMsg);
				if (svcName == null) {
					svcName = "";
				} else {
					svcName = svcName.trim();
				}
				this.tempProp.setProperty(HttpClientAdapterServiceKey.TRAN_CODE, svcName);
				if (logger.isInfo())
					logger.info(guidLogPrefix + " HTTP NKESA  svcName : " + svcName);

				// FRST_DMND_SYS_IP_VAL 로 라우팅하도록 함
				String operationEnv = getOperationEnv(this.reqEaiMsg);
				if (com.eactive.eai.common.server.Keys.EAI_LOCAL.equals(operationEnv)
						&& EAIServerManager.getInstance().isMCI()) {
					String firstServiceIp = getFirstRequestSysIp(this.reqEaiMsg);
					this.tempProp.setProperty(HttpClientAdapterServiceKey.LOCAL_CALL, HttpClientAdapterServiceKey.LOCAL_CALL_Y);
					this.tempProp.setProperty(HttpClientAdapterServiceKey.LOCAL_IP, firstServiceIp);
					if (logger.isInfo())
						logger.info(guidLogPrefix + " HTTP NKESA  LOCAL_CALL IP : " + firstServiceIp);
				}

				this.adptrMsgPtrnCd = adptGrpVO.getAdptrMsgPtrnCd();
				this.adptrMsgType = adptGrpVO.getMessageType();
				this.outboundProp.setProperty("MESSAGE_TYPE", this.adptrMsgType);
			} catch (Exception e) {
				throw new Exception("Target Adapter Fail (" + this.adapterGroupName + ") ", e);
			}

			// 하나캐피탈 POC 관련 추가
			// 계정계 호출 url 표준헤더에서 가져와 셋팅
			String targetUrl = this.callProp.getProperty("HTTP_URL");
			if (StringUtils.isNotBlank(targetUrl)) {
				this.outboundProp.setProperty("HTTP_URL", targetUrl);
			}

			if (com.eactive.eai.adapter.Keys.IF_STANDARD.equals(this.adptrMsgPtrnCd)) {
				// StandardMessage object -> message (FLAT|XML|JSON|?)
				String restOption = this.reqEaiMsg.getCurrentSvcMsg().getRestOption();
				setStandardRouteInfo(restOption);
				this.reqObject = makeStandardMessageData(this.reqEaiMsg, this.adptrMsgType, this.reqObject, this.outboundCharset);
			} 
			else if (com.eactive.eai.adapter.Keys.IF_SUBSTANDARD.equals(this.adptrMsgPtrnCd)) {
				this.reqObject = makeSubStandardMessageData(this.reqEaiMsg, this.adptrMsgType, this.reqObject, this.outboundCharset);
				if(this.reqObject instanceof String) {
					this.reqObject = ((String) this.reqObject).getBytes(this.outboundCharset);
				}
			}
			else {
				EAIServerManager eaiServerManager = EAIServerManager.getInstance();
				if (eaiServerManager.isTASEnabledEAIServer()
						&& EAIMessageKeys.TRANTYPE_TAS.equals(reqEaiMsg.getTranType())) {
					this.reqObject = SimHeaderUtil.addSimHeader(reqEaiMsg.getEAISvcCd(), getInstCode(reqEaiMsg), reqObject);
					if(logger.isDebug()) logger.debug(guidLogPrefix + " SIM LOG " + this.reqObject);
				}

				// 비표준 XML의 경우를 고려하여 XML Header의 유무를 확인
				// 변환을 수행하고 결과가 비표준 XML일 경우에만
				if (EAIMessageKeys.YES_FLAG.equals(this.reqEaiMsg.getCurrentSvcMsg().getCnvEn())
						&& MessageType.XML.equals(adptGrpVO.getMessageType())) {
					if (logger.isDebug()) {
						logger.debug(guidLogPrefix + " Add Xml Header Tag to NONSTANDARD XML Message");
					}

					if (this.reqObject instanceof String) {
						String reqString = (String) this.reqObject;
						if (!StringUtils.startsWith(reqString, "<?xml")) {
							reqString = "<?xml version=\"1.0\" encoding=\"" + this.outboundCharset + "\"?>\n"
									+ reqString;
							this.reqObject = reqString;
						}
					}
				}

				if (logger.isDebug())
					logger.debug(guidLogPrefix + " HTTP NONSTANDARD Request Message : "
							+ MessageUtil.toAdapterTypeString(this.reqObject, this.inboundCharset));
			}
			// TAS 선택시 시뮬레이터 url로 변경, HTT 어댑터도 RST 처럼 방식을 변경하였다.
			EAIServerManager eaiServerManager = EAIServerManager.getInstance();
			if (eaiServerManager.isTASEnabledEAIServer() && EAIMessageKeys.TRANTYPE_TAS.equals(reqEaiMsg.getTranType())) {
				PropManager manager = PropManager.getInstance();
				Properties prop = manager.getProperties(RouteKeys.SIM);
				String simAddr = prop.getProperty(RouteKeys.SIM_REST_MOCKSERVER);
				if (StringUtils.isBlank(simAddr)) {
					throw new Exception(String.format("Properties %s > %s not setted", RouteKeys.SIM,
							RouteKeys.SIM_REST_MOCKSERVER));
				}

				String url = StringUtils.removeEnd(simAddr, "/") + "/mockapi/" + this.reqEaiMsg.getEAISvcCd();
				this.outboundProp.put(HttpClientAdapterServiceKey.URL, url);
				this.tempProp.remove(HttpAdapterServiceKey.INBOUND_REWRITE_PATH);
				logger.debug("simUrl=" + url);
			}
		} catch (Exception e) {
			String[] msgArgs = new String[1];
			msgArgs[0] = this.reqEaiMsg.getEAISvcCd();
			String rspErrorCode = "RECEAIOHP022";
			String rspErrorMsg = ExceptionUtil.make(e, rspErrorCode, msgArgs);
			if (logger.isError())
				logger.error(guidLogPrefix + rspErrorMsg, e);
			this.resEaiMsg.setRspErr(rspErrorCode,rspErrorMsg);
			throw new Exception(rspErrorMsg);
		}
	}

	public void getTopicProperty() throws Exception {
		PropManager propManager = PropManager.getInstance();

		this.topicConFactory = propManager.getProperty(RouteKeys.GROUP_NAME,
				RouteKeys.ROUTING_TOPIC_CONNECTION_FACTORY);
		this.topicName = propManager.getProperty(RouteKeys.GROUP_NAME, RouteKeys.ROUTING_TOPIC);
//      this.timeout = this.reqEaiMsg.getCurrentSvcMsg().getTmoVl() * 1000; //180 * 1000;
		int iTimeoutValue = getTimeoutCodeToValue();
		this.timeout = iTimeoutValue * 1000;
		this.tracekey = this.reqEaiMsg.getCurrentSvcMsg().getKeyMgtMsgVl();

		if (ElinkConfig.isUseCacheTopic()) {
			this.future = new Future();
			try {
				ResponseMap.getInstance().put(this.tracekey, future);
			} catch (Exception e) {
				logger.error(guidLogPrefix + "Cannot start the Cache Response Future. - " + e.getMessage(), e);
				String[] msgArgs = new String[1];
				msgArgs[0] = this.reqEaiMsg.getEAISvcCd();
				String rspErrorCode = "RECEAIOHP060";
				String rspErrorMsg = ExceptionUtil.make(e, rspErrorCode, msgArgs);
				this.resEaiMsg.setRspErr(rspErrorCode,rspErrorMsg);
				throw new Exception(rspErrorMsg);
			}
		} else {
			jmsRespAction = new com.eactive.eai.common.worker.JMSListenerAction(this.topicConFactory, this.topicName,
					this.timeout);
			jmsRespAction.doInit(this.tracekey);
			this.future = new Future();
			try {
				jmsRespAction.doStart(future.getSlot());
			} catch (Exception e) {
				logger.error(guidLogPrefix + "Cannot start the JMSListenerAction. - " + e.getMessage(), e);
				String[] msgArgs = new String[1];
				msgArgs[0] = this.reqEaiMsg.getEAISvcCd();
				String rspErrorCode = "RECEAIOHP060";
				String rspErrorMsg = ExceptionUtil.make(e, rspErrorCode, msgArgs);
				this.resEaiMsg.setRspErr(rspErrorCode,rspErrorMsg);
				throw new Exception(rspErrorMsg);
			}
		}
	}

	public void performSend() throws Exception {
		try {
			String headerActionName = this.reqEaiMsg.getCurrentSvcMsg().getHdrRefClsName();
			String headerContolType = StringUtil.getNullStr(this.reqEaiMsg.getCurrentSvcMsg().getHdrCtrlDstcd());

			if (logger.isDebug()) {
				logger.debug(guidLogPrefix + " Header 로직을 실행합니다.");
				logger.debug(guidLogPrefix + " headerActionName :  [" + headerActionName + "]");
				logger.debug(guidLogPrefix + " 전송 Type :  [" + HeaderActionKeys.MESSAGE_SEND + "]");
				logger.debug(guidLogPrefix + " Header Control Type :  [" + headerContolType + "]");
			}

			HeaderAction action = HeaderActionFactory.createAction(headerActionName);

			if (this.tgtTranObject instanceof byte[]) {
				this.orgData = new byte[((byte[]) this.tgtTranObject).length];
				System.arraycopy(this.tgtTranObject, 0, this.orgData, 0, ((byte[]) this.tgtTranObject).length);

				this.tgtTranObject = action.excute(this.orgData, (byte[]) this.tgtTranObject,
						HeaderActionKeys.MESSAGE_SEND, headerContolType);

				if (logger.isDebug()) {
					logger.debug(guidLogPrefix + " this.orgMessage"
							+ MessageUtil.toAdapterTypeString((byte[]) this.tgtTranObject, this.inboundCharset));
				}

			} else {
				if (logger.isWarn()) {
					logger.warn(guidLogPrefix + " byte[] 만허용됩니다. 업무메시지타입을 확인하세요" + this.tgtTranObject);
				}
			}
			if (logger.isDebug()) {
				logger.debug(guidLogPrefix + " Header 로직을 종료합니다.");
			}
		} catch (Exception e) {
			String[] msgArgs = new String[1];
			msgArgs[0] = this.reqEaiMsg.getEAISvcCd();
			String rspErrorCode = "RECEAIOHP040";
			String rspErrorMsg = ExceptionUtil.make(e, rspErrorCode, msgArgs);
			if (logger.isError())
				logger.error(guidLogPrefix + rspErrorMsg, e);
			this.resEaiMsg.setRspErr(rspErrorCode,rspErrorMsg);
			throw new Exception(rspErrorMsg);
		}
	}

	public void performRecv() throws Exception {
		try {
			String headerActionName = this.reqEaiMsg.getCurrentSvcMsg().getHdrRefClsName();
			String headerContolType = StringUtil.getNullStr(this.reqEaiMsg.getCurrentSvcMsg().getHdrCtrlDstcd());

			if (logger.isDebug()) {
				logger.debug(guidLogPrefix + " Header 로직을 실행합니다.");
				logger.debug(guidLogPrefix + " headerActionName :  [" + headerActionName + "]");
				logger.debug(guidLogPrefix + " 전송 Type :  [" + HeaderActionKeys.MESSAGE_RECV + "]");
				logger.debug(guidLogPrefix + " Header Control Type :  [" + headerContolType + "]");
			}

			HeaderAction action = HeaderActionFactory.createAction(headerActionName);
			String bizData = this.resEaiMsg.getStandardMessage().getBizData();

			if (bizData != null && bizData.length() > 0) {
				this.tgtTranObject = bizData;
			}

			if (this.tgtTranObject instanceof byte[]) {
				this.tgtTranObject = action.excute(this.orgData, (byte[]) this.tgtTranObject,
						HeaderActionKeys.MESSAGE_RECV, headerContolType);
				this.resEaiMsg.getStandardMessage().setBizData(tgtTranObject, this.inboundCharset);

				if (logger.isDebug()) {
					logger.debug(guidLogPrefix + " this.tgtTranObject"
							+ MessageUtil.toAdapterTypeString((byte[]) this.tgtTranObject, this.outboundCharset));
				}
			} else {
				if (logger.isWarn()) {
					logger.warn(guidLogPrefix + " byte[] 만허용됩니다. 업무메시지타입을 확인하세요" + this.tgtTranObject);
				}
			}
			if (logger.isDebug()) {
				logger.debug(guidLogPrefix + " Header 로직을 종료합니다.");
			}
		} catch (Exception e) {
			String[] msgArgs = new String[1];
			msgArgs[0] = this.reqEaiMsg.getEAISvcCd();
			String rspErrorCode = "RECEAIOHP040";
			String rspErrorMsg = ExceptionUtil.make(e, rspErrorCode, msgArgs);
			if (logger.isError())
				logger.error(guidLogPrefix + rspErrorMsg, e);
			this.resEaiMsg.setRspErr(rspErrorCode,rspErrorMsg);
			throw new Exception(rspErrorMsg);
		}
	}

	public void getBizMessage() throws Exception {

	}

	public void storeMessage() throws Exception {
		// 비동기-비동기 거래 수동이 표준이 아닌 경우
		// 원거래복원 여부가 '1' 일 경우
		String recoverYn = getRecoverYn(reqEaiMsg);
		if (logger.isDebug()) {
			logger.debug(guidLogPrefix + "Message 복원 Flag [" + recoverYn + "]");
		}
		if (EAIMessageKeys.ASYNC_SVC.equals(this.reqEaiMsg.getSvcTsmtUsgTp())
				&& !com.eactive.eai.adapter.Keys.IF_STANDARD.equals(this.adptrMsgPtrnCd)
				&& STDMessageKeys.RECOVER_YN_YES.equals(recoverYn)) {

			try {
				String keyMgtMsgCtnt = this.reqEaiMsg.getCurrentSvcMsg().getKeyMgtMsgVl();
				if (logger.isDebug()) {
					logger.debug(guidLogPrefix + "Message 복원 실행 KEY[" + keyMgtMsgCtnt + "]");
				}
				String extBizCd = this.reqEaiMsg.getExtBizCd();
				STDMessageMapper.storeMessageHeader(keyMgtMsgCtnt, this.reqEaiMsg.getStandardMessage(), extBizCd, this.inAdapterMsgType);				
			} catch (Exception e) {
				if (logger.isError()) {
					logger.error(guidLogPrefix + "Message 저장 중 에러 발생", e);
				}

				String[] msgArgs = new String[1];
				msgArgs[0] = this.reqEaiMsg.getEAISvcCd();
				String rspErrorCode = "RECEAIOSP011";
				String rspErrorMsg = ExceptionUtil.make(e, rspErrorCode, msgArgs);
				if (logger.isError())
					logger.error(guidLogPrefix + rspErrorMsg, e);
				this.resEaiMsg.setRspErr(rspErrorCode,rspErrorMsg);
				throw new RuntimeException(rspErrorCode);
			}
		}
	}

	public void waitCheckForSync() throws Exception {
		// Sync - Sync 거래중 Wait 메시지가 올경우 대비
		// Async -Sync 는 Flow Control에서 처리 함
		if (com.eactive.eai.adapter.Keys.IF_STANDARD.equals(this.adptrMsgPtrnCd) && resObject != null) {
			if (EAIMessageKeys.SYNC_SVC.equals(this.reqEaiMsg.getSvcTsmtUsgTp())) {
				StandardMessage standardMessage = null;
				StandardMessageManager standardManager = StandardMessageManager.getInstance();
				StandardReader reader = null;
				try {
					standardMessage = standardManager.getStandardMessage();
					reader = standardManager.getReader(this.adptrMsgType);
					reader.parse(standardMessage, resObject);
					//표준 전문 파싱 후 어댑터의 charset을 설정한다.
					standardMessage.setBizDataCharset(outboundCharset);
				}catch(Exception e) {
					logger.error("standardMessage parsing error " + e.getMessage(),e);
					return ;
				}
				boolean isWait = standardManager.getMessageCoordinator().coordinateIsWaitCheckForSync(standardMessage);
				if (isWait) {
					getTopicProperty();
					try {
						setTopicResult();
					}catch (Exception e) {
						executeTimeout();
					}
				}
			}
		}
	}

	@Override
	public void transControlHeaderTrnsformSinglesRes() throws Exception {

	}

	protected void setStandardRouteInfo(String routeOption) throws JsonProcessingException {
		if(StringUtils.isBlank(routeOption)) {
			return ;
		}
		JsonNode rootNode = objectMapper.readTree(routeOption);
		JsonNode standardCommonFields = rootNode.get("standardCommonFields");

		if (standardCommonFields != null && standardCommonFields.isObject()) {
			standardCommonFields.fields().forEachRemaining(field -> {
				String key = field.getKey();
				String value = field.getValue().asText();

				StandardMessage standardMessage = this.reqEaiMsg.getStandardMessage();
				standardMessage.setData(key, value);
			});
		}
	}
}
