package com.eactive.eai.outbound;
 
import java.net.SocketTimeoutException;
import java.util.Map;
import java.util.Properties;

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.handler.AdapterErrorMessageHandler;
import com.eactive.eai.adapter.handler.AdapterErrorMessageHandlerFactory;
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.adapter.http.dynamic.HttpAdapterServiceSupport;
import com.eactive.eai.common.EAIKeys;
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.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.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.util.PropertiesUtil;
import com.ext.eai.common.stdmessage.STDMessageKeys;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import io.github.resilience4j.circuitbreaker.CallNotPermittedException;
import io.github.resilience4j.circuitbreaker.CircuitBreaker;

public class RESTProcess extends HTTPProcess {
	static final long serialVersionUID = 1L;

	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);
		
		this.tempProp.put("API_SERVICE_CODE", this.reqEaiMsg.getEAISvcCd());
		this.tempProp.put("OUT_REQ_EAI_MSG", this.reqEaiMsg);
		this.tempProp.put("OUT_REQ_STD_MSG", this.reqEaiMsg.getStandardMessage());
		
		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);
		} 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 (CallNotPermittedException e) {
			String[] msgArgs = new String[1];
			msgArgs[0] = this.reqEaiMsg.getEAISvcCd();
			String rspErrorCode = "RECEAIOHP201";
			String rspErrorMsg = ExceptionUtil.make(e, rspErrorCode, msgArgs);
			if (logger.isError())
				logger.error(guidLogPrefix + rspErrorMsg, e);
			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 {
			// REST 는 TEST Call을 할수 없음.20200813.최준호
			if (logger.isDebug()) {
				logger.debug(guidLogPrefix + " UUID[" + this.reqEaiMsg.getSvcOgNo() + "] 수동시스템 오류 ");
			}
		}
	}

	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 = setRcvLogInfo(resEaiMsg, this.adptrMsgType, this.resObject, this.outboundCharset);
					this.resObject = resEaiMsg.getStandardMessage().getBizData();
				} 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().getBizData();
				} 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);
				}
			}
		}
	}

	public void setTopicResult() throws Exception {
		try {
			this.jmsRespObject = future.value(this.timeout);
			if (this.jmsRespObject == null) {
				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().getBizDataBytes();
		} else if (this.jmsRespObject instanceof byte[]) {
			this.resObject = (byte[]) this.jmsRespObject;
		} else {
			this.resObject = new byte[0];
		}

	}

	public void init() throws Exception {
		this.prop = null;
		this.tempProp = new Properties();
		this.adapterName = this.callProp.getProperty(com.eactive.eai.adapter.Keys.OUT_ADAPTER_NAME);
		
		this.resEaiMsg = this.reqEaiMsg;
		this.adapterGroupName = reqEaiMsg.getCurrentSvcMsg().getPsvSysItfTp();

		// DefaultProcess 이관시 누락된 부분 추가
		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()) {
				if (this.prop == null) {
					logger.warn(guidLogPrefix + "Source Adapter is null, TAS Inbound ");
				} else {
					logger.warn(guidLogPrefix + "Source Adapter is null, TAS Inbound = "
							+ this.prop.getProperty(Processor.TAS_ADAPTER_GROUP_NAME));
				}
			}
			this.inAdapterMsgType = MessageType.ASC;
		} else {
			this.inAdapterMsgType = inAdptGrpVO.getMessageType();
		}
	}

	public void setSendMsg() throws Exception {
		try {
			// 200 로그를 위한 변환된 메시지부를 설정
			this.reqEaiMsg.getStandardMessage().setBizData(tgtTranObject, this.outboundCharset);

			if (this.tgtTranObject instanceof String) {
				this.reqObject = (String) this.tgtTranObject;
			} else {
				throw new Exception("Invlid Transform output message (" + 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);
			}
			String restOption = null;
			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());

				restOption = this.reqEaiMsg.getCurrentSvcMsg().getRestOption();
				if (restOption != null) {
					this.tempProp.setProperty(HttpClientAdapterServiceKey.REST_OPTION, restOption);
				}
				String toutval = String.valueOf(this.reqEaiMsg.getCurrentSvcMsg().getTmoVl());
				if (StringUtils.isNotBlank(toutval)) {
					this.tempProp.setProperty(HttpClientAdapterServiceKey.TOUTVAL, toutval);
				}

				PropertiesUtil.copyPropertyIfPresent(this.callProp, this.tempProp, TransactionContextKeys.TRANSACTION_UUID);
				PropertiesUtil.copyPropertyIfPresent(this.callProp, this.tempProp, HttpAdapterServiceKey.INBOUND_HEADER);
				PropertiesUtil.copyPropertyIfPresent(this.callProp, this.tempProp, HttpAdapterServiceKey.INBOUND_METHOD);
				PropertiesUtil.copyPropertyIfPresent(this.callProp, this.tempProp, HttpAdapterServiceKey.INBOUND_REWRITE_PATH);
				PropertiesUtil.copyPropertyIfPresent(this.callProp, this.tempProp, HttpAdapterServiceKey.INBOUND_QUERY_STRING);
				PropertiesUtil.copyPropertyIfPresent(this.callProp, this.tempProp, HttpAdapterServiceKey.INBOUND_PATH_VARIABLES);
				PropertiesUtil.copyPropertyIfPresent(this.callProp, this.tempProp, HttpAdapterServiceKey.INBOUND_REMOTE_ADDR);
				PropertiesUtil.copyPropertyIfPresent(this.callProp, this.tempProp, HttpAdapterServiceKey.INBOUND_SCHEME);
				PropertiesUtil.copyPropertyIfPresent(this.callProp, this.tempProp, HttpAdapterServiceKey.INBOUND_REQUESTED_TIME);   // jwhong
				PropertiesUtil.copyPropertyIfPresent(this.callProp, this.tempProp, HttpAdapterServiceKey.GUID);   // jwhong
				PropertiesUtil.copyPropertyIfPresent(this.callProp, this.tempProp, HttpAdapterServiceKey.INBOUND_TOKEN);   // jwhong
				PropertiesUtil.copyPropertyIfPresent(this.callProp, this.tempProp, HttpAdapterServiceSupport.PROPERTIES_NAME_CLIENT_ID);   // jwhong
				PropertiesUtil.copyPropertyIfPresent(this.callProp, this.tempProp, TransactionContextKeys.X_LOAN_TOKEN);
				
				String svcName = getServiceId(this.reqEaiMsg);
				if (svcName == null) {
					svcName = "";
				} else {
					svcName = svcName.trim();
				}
				this.tempProp.setProperty(HttpClientAdapterServiceKey.TRAN_CODE, svcName);

				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);
			}

			// 표준메시지 방식일 경우 KESA메시지에 업무메시지를 설정하여 전달한다.
			// migration - boolean 값이 아니라 [S, N, C] 값을 가짐
			if (com.eactive.eai.adapter.Keys.IF_STANDARD.equals(this.adptrMsgPtrnCd)) {
				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 {
				// 변환을 수행하고 결과가 비표준 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");
					}

					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로 변경
			EAIServerManager eaiServerManager = EAIServerManager.getInstance();
			if (eaiServerManager.isTASEnabledEAIServer() && EAIMessageKeys.TRANTYPE_TAS.equals(reqEaiMsg.getTranType())
					&& StringUtils.equals(adptGrpVO.getType(), "RST")) {
				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.put("tranType", reqEaiMsg.getTranType());
				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);
		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 {
		// setRcvLogInfo() 에서 이미 호출됨
	}

	public void storeMessage() throws Exception {

	}
	
	public void setOutboundErrorMessage() throws Exception {
		this.logPssSno = TranLogUtil.getResLogSeq(this.svcPssTp, this.svcPssSeq, this.isComp);

		boolean setResObject = false;
		// 에러에 대한 응답메시지
		if(this.tempProp.get(HttpAdapterServiceKey.OUTBOUND_PROPERTY_MAP) instanceof Map) {
			@SuppressWarnings("unchecked")
			Map<String, Object> map = (Map<String, Object>) this.tempProp.get(HttpAdapterServiceKey.OUTBOUND_PROPERTY_MAP);
			this.callProp.put(HttpAdapterServiceKey.OUTBOUND_PROPERTY_MAP, map);
			
			// OUTBOUND_PROPERTY_MAP 이 있는 경우, 즉 타겟서버와 통신은 정상적으로 이루진 경우 처리한다.
			AdapterGroupVO outboundAdapterGroupVO = AdapterManager.getInstance().getAdapterGroupVO(adapterGroupName);
			if (outboundAdapterGroupVO != null) {
				AdapterVO outboundAdapterVo = null;
				if(adapterName != null)
					outboundAdapterVo = outboundAdapterGroupVO.getAdapterVO(adapterName);
				else
					outboundAdapterVo = outboundAdapterGroupVO.nextAdapterVO();
				
				if (outboundAdapterVo != null) {
					String errorHandlerClass = AdapterPropManager.getInstance().getProperty(
							outboundAdapterVo.getPropGroupName(), "ERR_MSG_HANDLER");
					if (StringUtils.isNotBlank(errorHandlerClass)) {
						if (logger.isInfo())
							logger.info("ExceptionHandler] errorSyncSend ERR_MSG_HANDLER=" + errorHandlerClass);
						AdapterErrorMessageHandler handler = AdapterErrorMessageHandlerFactory.createHandler(errorHandlerClass);
						this.resObject = handler.generateOutboundErrorResponseMessage(adapterGroupName, adapterGroupName,
								callProp, this.reqObject, this.resEaiMsg);
						setResObject = true;
					}
				}
			}
		}

		if (!setResObject) {
			this.resObject = "";
		}
		StandardMessage standardMessage = this.resEaiMsg.getStandardMessage();
		standardMessage.setBizData(this.resObject, this.inboundCharset);

	}

}
