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

import java.io.ByteArrayInputStream;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Formatter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.springframework.http.HttpHeaders;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import com.eactive.eai.adapter.http.EntityEnclosingDeleteMethod;
import com.eactive.eai.adapter.http.EntityEnclosingGetMethod;
import com.eactive.eai.adapter.http.HttpMemoryLogger;
import com.eactive.eai.adapter.http.HttpMethodType;
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceSupport;
import com.eactive.eai.adapter.http.client.HttpClientAdapterVO;
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
import com.eactive.eai.adapter.http.dynamic.impl.HttpAdapterServiceBypass;
import com.eactive.eai.adapter.http.secure.CustomHttpsSocketFactory;
import com.eactive.eai.adapter.http.secure.EasySSLProtocolSocketFactory;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.util.CommonLib;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.openbanking.eai.common.token.AccessTokenManager;
import com.openbanking.eai.common.token.AccessTokenVO;
import com.openbanking.eai.common.token.OAuth2AccessTokenVO;

public class HttpClientAdapterServiceBypass extends HttpClientAdapterServiceSupport
		implements HttpClientAdapterServiceKey {
	public static final String TYPE_BYPASS_REQUEST = "bypassRequest";
	public static final String REST_OPTION = "REST_OPTION";

	protected boolean doSendUrlFragment = true;
	protected boolean doHandleCompression = false;
	protected boolean doForwardIP = true;

	@SuppressWarnings({ "deprecation", "unchecked" })
	public Object execute(Properties prop, Object data, Properties tempProp) throws Exception {
		HttpClientAdapterVO vo = super.setting(prop, tempProp);

		boolean useAdapterToken = StringUtils.equalsIgnoreCase(prop.getProperty("ADAPTER_TOKEN_USE_YN", "N"), "Y");

		// 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번대

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

		JSONObject restOptionObject = parseJson(restOptionData);

		String adapterTokenUseYn = (String) restOptionObject.get("adapterTokenUseYn");
		if (StringUtils.isNotBlank(adapterTokenUseYn)) { // interface 에 설정된게 우선한다.
			useAdapterToken = StringUtils.equalsIgnoreCase(adapterTokenUseYn, "Y");
		}
		
		String inboundMethod = tempProp.getProperty(HttpAdapterServiceKey.INBOUND_METHOD, "POST");
		String inboundRewritePath = tempProp.getProperty(HttpAdapterServiceKey.INBOUND_REWRITE_PATH, "");
		String inboundQueryString = tempProp.getProperty(HttpAdapterServiceKey.INBOUND_QUERY_STRING, "");
		Properties inboundHeaders = (Properties) tempProp.get(HttpAdapterServiceKey.INBOUND_HEADER);
		Map<String, String> inboundPathVariables = (Map<String, String>) tempProp
				.get(HttpAdapterServiceKey.INBOUND_PATH_VARIABLES);

		String restMethod = (String) restOptionObject.get("method");
		if (StringUtils.isBlank(restMethod)) {
			restMethod = inboundMethod;
		}
		
		String url = getRewriteUrl(vo, inboundRewritePath, inboundQueryString, restOptionObject, inboundPathVariables);
		if (logger.isDebug()) {
			logger.debug("HttpClientAdapterServiceBypass] url =  [" + url + "]");
		}

		HttpClient mclient = this.client;
		
		HttpMethodBase method = generateMethod(restMethod, url);

		assignRequestHeaders(method, inboundHeaders, tempProp);

		if (hasBody(data, inboundHeaders)) {
			if (data instanceof byte[]) {
				((EntityEnclosingMethod) method).setRequestBody(new ByteArrayInputStream((byte[]) data));
			} else if (data instanceof String) {
				((EntityEnclosingMethod) method).setRequestBody((String) data);
			}
		}

		String contentType = (String) restOptionObject.get("contentType");
		if (StringUtils.isBlank(contentType) && inboundHeaders != null) {
			contentType = getIgnoreCaseProp(inboundHeaders, HttpHeaders.CONTENT_TYPE);
			contentType = StringUtils.substringBefore(contentType, ";");
		}
		configureHttpClient(mclient, method, vo, url, contentType);

		OAuth2AccessTokenVO accessToken = null;
		if (useAdapterToken) {
			AccessTokenManager tokenManager = AccessTokenManager.getInstance();
			accessToken = (OAuth2AccessTokenVO) tokenManager.getAccessTokenVO(vo.getAdapterGroupName());

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

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

			setAuthHeaders(method, accessToken);

			if (logger.isDebug()) {
				logger.debug("HttpClientAdapterServiceBypass] SEND (" + vo.getAdapterGroupName()
						+ ") RequestHeader [Authorization=" + method.getRequestHeader("Authorization") + "]");
			}
		}

		int status = -1;

		try {
			StopWatch stopWatch = new StopWatch();
			stopWatch.start();

			byte[] responseMessage = null;

			if (vo.getTraceLevel() >= 3) {
				HttpMemoryLogger.txlog(vo.getAdapterGroupName() + vo.getAdapterName(),
						"SEND [Bypass Request..]" + CommonLib.getDumpMessage(data));
			}
			try {
				if (logger.isDebug()) {
					logger.debug("[method getName]" + method.getName());
					logger.debug("[method getRequestCharSet]" + method.getRequestCharSet());
					logger.debug("[method getRequestHeaders]" + method.getRequestHeaders().toString());
					logger.debug("[method getQueryString]" + method.getQueryString());
					logger.debug("[method getParams]" + method.getParams().toString());
					logger.debug("[method getURI]" + method.getURI());
				}
				if (vo.getUrl() != null && vo.getUrl().startsWith("https")) {
					Protocol.registerProtocol("https",
							new Protocol("https", new CustomHttpsSocketFactory(new EasySSLProtocolSocketFactory()), 443));
				}				
				status = mclient.executeMethod(method);
				if (logger.isDebug()) {
					logger.debug("[received status]" + status);
				}
			} catch (ConnectException e) {
				responseMessage = method.getResponseBody();
				if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
					logger.debug("HttpClientAdapterServiceBypass] responseType =" + vo.getResponseType());
					logger.debug("HttpClientAdapterServiceBypass] RECV (" + vo.getAdapterGroupName() + ") = "
							+ CommonLib.getDumpMessage(responseMessage));
				}
				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;

			if (status == 200) {
				responseMessage = method.getResponseBody();
				if (useAdapterToken && StringUtils.equals(tokenErrorHttpStatusCode, "200")) {
					needReissue = checkTokenRetry(responseMessage, tokenErrorCodeKey, tokenErrorCodeValues,
							vo.getEncode());
				}
			} else if (status >= 400 && status < 500) {
				responseMessage = method.getResponseBody();
				if (useAdapterToken) {
					needReissue = checkTokenRetry(responseMessage, tokenErrorCodeKey, tokenErrorCodeValues,
							vo.getEncode());
				}

				if (!needReissue) {
					// body 값이 없을때만 exception 처리하고, body가 있으면 bypass 한다.
					if (responseMessage == null || responseMessage.length == 0) {
						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(), url, method, responseMessage);
						throw new Exception(errMsg);
					}
				}
			} else {
				responseMessage = method.getResponseBody();
				// body 값이 없을때만 exception 처리하고, body가 있으면 bypass 한다.
				if (responseMessage == null || responseMessage.length == 0) {
					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(), url, method, responseMessage);
					throw new Exception(errMsg);
				}
			}

			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("HttpClientAdapterServiceBypass] 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);
					method.setRequestHeader("Authorization", newAccessToken.getAuthorization());

					setAuthHeaders(method, newAccessToken);

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

					try {
						status = mclient.executeMethod(method);
					} catch (ConnectException e) {
						throw new Exception("retry excuteMethod Exceptioin = " + e.getMessage());
					}

					if (status == 200) {
						responseMessage = method.getResponseBody();
					} else {
						responseMessage = method.getResponseBody();
						// body 값이 없을때만 exception 처리하고, body가 있으면 bypass 한다.
						if (responseMessage == null || responseMessage.length == 0) {
							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(), url, method,
									responseMessage);
							throw new Exception(errMsg);
						}
					}

					if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
						logger.debug("HttpClientAdapterServiceBypass] RETRY responseType =" + vo.getResponseType());
						logger.debug("HttpClientAdapterServiceBypass] RETRY RECV (" + vo.getAdapterGroupName() + ") = "
								+ CommonLib.getDumpMessage(responseMessage));
					}
				}
			}

			if (vo.getTraceLevel() >= 3) {
				HttpMemoryLogger.txlog(vo.getAdapterGroupName() + vo.getAdapterName(),
						"RECV [Bypass Request..]" + CommonLib.getDumpMessage(responseMessage));
			}
			assignRelayDataToInbound(tempProp, method.getResponseHeaders(), status);
			return responseMessage;
		} catch (SocketTimeoutException ste) { // Read Timeout :: HttpClient 3.1일 경우
			if (vo.getTraceLevel() >= 3) {
				HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
						"HttpClientAdapterServiceBypass] SocketTimeoutException (" + vo.getAdapterGroupName() + ") : "
								+ ste.toString(),
						ste);
			}
			logger.error("HttpClientAdapterServiceBypass] SocketTimeoutException (" + vo.getAdapterGroupName() + ") : "
					+ ste.toString(), ste);
			throw ste;
		} catch (ConnectException ce) {
			if (vo.getTraceLevel() >= 3) {
				HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
						"HttpClientAdapterServiceBypass] Connection Exception (" + vo.getAdapterGroupName() + ") : "
								+ ce.toString(),
						ce);
			}
			logger.error("HttpClientAdapterServiceBypass] 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(
					"HttpClientAdapterServiceBypass] Exception (" + vo.getAdapterGroupName() + ") : " + e.toString(),
					e);
			throw e;
		} finally {
			method.releaseConnection();
			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 boolean hasBody(Object data, Properties inboundHeaders) {
		if (data == null) {
			return false;
		}

//		// spec: RFC 2616, sec 4.3
//		String contentLength = getIgnoreCaseProp(inboundHeaders, HttpHeaders.CONTENT_LENGTH);
//		String transferEncoding = getIgnoreCaseProp(inboundHeaders, HttpHeaders.TRANSFER_ENCODING);
//		if (StringUtils.isNotBlank(contentLength) || StringUtils.isNotBlank(transferEncoding)) {
//			return true;
//		}
//		return false;
		
		// client adapter 단독으로 사용 가능하게 수정
		return true;
	}

	private HttpMethodBase generateMethod(String restMethod, String url) {
		HttpMethodBase method = null;
		switch (HttpMethodType.getValue(restMethod)) {
		case GET:
			method = new EntityEnclosingGetMethod(url);
			break;
		case DELETE:
			method = new EntityEnclosingDeleteMethod(url);
			break;
		case POST:
			method = new PostMethod(url);
			break;
		case PUT:
			method = new PutMethod(url);
			break;
		default:
			// set default method
			method = new PostMethod(url);
			break;
		}
		return method;
	}

	private String getRewriteUrl(HttpClientAdapterVO vo, String inboundRewritePath, String queryString,
			JSONObject restOptionObject, Map<String, String> inboundPathVariables) {
		String fragment = null;
		if (StringUtils.isNotBlank(queryString)) {
			int fragIdx = queryString.indexOf('#');
			if (fragIdx >= 0) {
				fragment = queryString.substring(fragIdx + 1);
				queryString = queryString.substring(0, fragIdx);
			}
		}
		
		String restExtraPath = (String) restOptionObject.get("extraPath");
		if (StringUtils.isBlank(restExtraPath)) {
			StringBuilder uri = new StringBuilder(500);
			uri.append(vo.getUrl()).append(inboundRewritePath);

			if (StringUtils.isNotBlank(queryString)) {
				uri.append('?');
				uri.append(encodeUriQuery(queryString, false));
			}

			if (doSendUrlFragment && fragment != null) {
				uri.append('#');
				uri.append(encodeUriQuery(fragment, false));
			}

			return uri.toString();
		} else {
			String type = (String) restOptionObject.get("type");
			String url = getUrl(vo.getUrl(), restExtraPath);

			if (StringUtils.equalsIgnoreCase(type, HttpClientAdapterServiceRest.TYPE_VARIABLE_URL_REQUEST)) {
				inboundPathVariables = mergeInboundPathVariables(inboundPathVariables, queryString);
				List<String> urlVariableValueList = new ArrayList<>();
				JSONArray uriVariables = (JSONArray) restOptionObject.get("uriVariables");
				if (uriVariables != null && !uriVariables.isEmpty() && inboundPathVariables != null
						&& !inboundPathVariables.isEmpty()) {
					for (Object tempObject : uriVariables) {
						String urlVaribleId = (String) tempObject;
						String uriVariableValue = inboundPathVariables.get(urlVaribleId);
						urlVariableValueList.add(uriVariableValue);
					}

					if (!urlVariableValueList.isEmpty()) {
						UriComponents uriComponents = UriComponentsBuilder.fromUriString(url).build();
						Object[] urls = urlVariableValueList.toArray();
						url = uriComponents.expand(urls).toUriString();
					}
				}
			} else {
				if (StringUtils.isNotBlank(queryString)) {
					url += "?" + encodeUriQuery(queryString, false);
				}

				if (doSendUrlFragment && fragment != null) {
					url += "#" + encodeUriQuery(fragment, false);
				}
			}

			return url;
		}
	}
	
	private Map<String, String> mergeInboundPathVariables(Map<String, String> inboundPathVariables,
			String queryString) {
		if (StringUtils.isBlank(queryString)) {
			return inboundPathVariables;
		}

		if (inboundPathVariables == null) {
			inboundPathVariables = new LinkedHashMap<>();
		}

		String[] pairs = queryString.split("&");
		for (String pair : pairs) {
			int idx = pair.indexOf("=");
			// URLDecoder.decode 필요??
			inboundPathVariables.put(pair.substring(0, idx), pair.substring(idx + 1));
		}

		return inboundPathVariables;
	}

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

		return targetUrl;
	}

	protected CharSequence encodeUriQuery(CharSequence in, boolean encodePercent) {
		// Note that I can't simply use URI.java to encode because it will escape
		// pre-existing escaped things.
		StringBuilder outBuf = null;
		Formatter formatter = null;
		for (int i = 0; i < in.length(); i++) {
			char c = in.charAt(i);
			boolean escape = true;
			if (c < 128) {
				if (asciiQueryChars.get(c) && !(encodePercent && c == '%')) {
					escape = false;
				}
			} else if (!Character.isISOControl(c) && !Character.isSpaceChar(c)) {// not-ascii
				escape = false;
			}
			if (!escape) {
				if (outBuf != null)
					outBuf.append(c);
			} else {
				// escape
				if (outBuf == null) {
					outBuf = new StringBuilder(in.length() + 5 * 3);
					outBuf.append(in, 0, i);
					formatter = new Formatter(outBuf);
				}
				// leading %, 0 padded, width 2, capital hex
				formatter.format("%%%02X", (int) c);// TODO
			}
		}
		return outBuf != null ? outBuf : in;
	}

	protected static final BitSet asciiQueryChars;
	static {
		char[] c_unreserved = "_-!.~'()*".toCharArray();// plus alphanum
		char[] c_punct = ",;:$&+=".toCharArray();
		char[] c_reserved = "/@".toCharArray();// plus punct. Exclude '?'; RFC-2616 3.2.2. Exclude '[', ']';
												// https://www.ietf.org/rfc/rfc1738.txt, unsafe characters
		asciiQueryChars = new BitSet(128);
		for (char c = 'a'; c <= 'z'; c++)
			asciiQueryChars.set(c);
		for (char c = 'A'; c <= 'Z'; c++)
			asciiQueryChars.set(c);
		for (char c = '0'; c <= '9'; c++)
			asciiQueryChars.set(c);
		for (char c : c_unreserved)
			asciiQueryChars.set(c);
		for (char c : c_punct)
			asciiQueryChars.set(c);
		for (char c : c_reserved)
			asciiQueryChars.set(c);

		asciiQueryChars.set('%');// leave existing percent escapes in place
	}

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

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

		headerProp.put(HttpAdapterServiceBypass.HTTP_STATUS, String.valueOf(status));

		Map<String, Object> map = new HashMap<String, Object>();
		map.put(HttpAdapterServiceKey.OUTBOUND_RESPONSE_HEADERS, headerProp);

		prop.put(HttpAdapterServiceKey.OUTBOUND_PROPERTY_MAP, map);
	}

	private void setAuthHeaders(HttpMethodBase method, OAuth2AccessTokenVO accessToken) throws Exception {
		method.setRequestHeader("Authorization",
				String.format("%s %s", AccessTokenVO.BEARER_TYPE, accessToken.getAccessToken()));
	}

	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("HttpClientAdapterServiceBypass] checkTokenRetry error=" + e.getMessage());
		}

		return false;
	}

	private void assignRequestHeaders(HttpMethodBase method, Properties headerProp, Properties inProp) {
		if (headerProp == null) {
			return;
		}

		for (Entry<Object, Object> e : headerProp.entrySet()) {
			String key = (String) e.getKey();
			String value = (String) e.getValue();

			if (StringUtils.equalsAnyIgnoreCase(key, HttpAdapterServiceBypass.HOP_BY_HOP_HEADERS)
					|| StringUtils.equalsIgnoreCase(key, HttpHeaders.CONTENT_LENGTH)) {
				continue;
			}

			if (doHandleCompression && StringUtils.equalsIgnoreCase(key, HttpHeaders.ACCEPT_ENCODING)) {
				continue;
			}

			method.setRequestHeader(key, value);

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

		if (doForwardIP) {
			String forHeaderName = "X-Forwarded-For";
			String forHeader = inProp.getProperty(HttpAdapterServiceKey.INBOUND_REMOTE_ADDR);
			if (StringUtils.isNotBlank(forHeader)) {
				String existingForHeader = headerProp.getProperty(forHeaderName);
				if (existingForHeader != null) {
					forHeader = existingForHeader + ", " + forHeader;
				}
				method.setRequestHeader(forHeaderName, forHeader);
			}

			String protoHeaderName = "X-Forwarded-Proto";
			String protoHeader = inProp.getProperty(HttpAdapterServiceKey.INBOUND_SCHEME);
			if (StringUtils.isNotBlank(protoHeader)) {
				method.setRequestHeader(protoHeaderName, protoHeader);
			}
		}
	}

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

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

	public static final String getIgnoreCaseProp(Properties prop, String key) {
		if (prop == null) {
			return null;
		}

		for (Entry<Object, Object> e : prop.entrySet()) {
			if (StringUtils.equalsIgnoreCase(key, (String) e.getKey())) {
				return (String) e.getValue();
			}
		}

		return null;
	}
}
