package kr.co.kihyun.beans.batch;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//import net.sf.jmimemagic.Magic;
//import net.sf.jmimemagic.MagicException;
//import net.sf.jmimemagic.MagicMatch;
//import net.sf.jmimemagic.MagicMatchNotFoundException;
//import net.sf.jmimemagic.MagicParseException;

import org.springframework.dao.*;

public class HttpClient {

    private static Logger logger = LoggerFactory.getLogger("XYZHttpClient");

    private String boundryKey = "--------------------------------CORDIAL";

    private EntityBuilder          entityBuilder    = null;
    private MultipartEntityBuilder multipartBuilder = null;

    private String sRequestedUrl = "";

    private List<BasicNameValuePair> mHttpDataForRequestLogin = null;
    private List<BasicNameValuePair> mHttpDataForRequestPost  = null;

    private HttpClientContext mHttpClientContext = null;

    private CloseableHttpClient mHttpClient  = null;
    private RequestConfig       globalConfig = null;
    private BasicCookieStore    mCookieStore = null;

    private String mLTPAToken = "";

    private boolean mIsAnonymous = false;
    private boolean mIsDomino    = false;

    private String mHttpRedirectedUrl = "";

    private String mHttpStatus   = "";
    private String mHttpProtocol = "";
    private String mHttpHost     = "";
    private String mHttpPort     = "";

    private String mHttpUserID       = "";
    private String mHttpUserPassword = "";

    private String mHttpLoginURL  = "/names.nsf?login";
    private String mHttpLogoutURL = "/names.nsf?logout";

    public HttpClient() {
    }

    public HttpClient(boolean pIsAnonymous, boolean pIsDomino, String pProtocol, String pHost, String pPort,
            String pUserID, String pPassword) {
        mIsAnonymous = pIsAnonymous;
        mIsDomino = pIsDomino;
        mHttpProtocol = pProtocol;
        mHttpHost = pHost;
        mHttpPort = pPort;
        mHttpUserID = pUserID;
        mHttpUserPassword = pPassword;

        initialize();
    }

    private String changeToFullURL(String pURL) {
        String strURL = pURL;

        if (strURL.startsWith("/")) {
            strURL = mHttpProtocol + "://" + mHttpHost
                    + (mHttpPort.equalsIgnoreCase("80") || mHttpPort.equalsIgnoreCase("443") ? "" : ":" + mHttpPort)
                    + strURL;
        }

        sRequestedUrl = strURL;

        return strURL;
    }

    // --------------------------------------------------
    // Directory & File Handling
    public boolean createDirectory(String pDirPath) {
        File td = new File(pDirPath);
        return td.mkdirs();
    }

    public boolean deleteDirectory(String pLocalPath) {
        boolean isDeleteSuccess = false;

        File fileToDelete = new File(pLocalPath);

        if (fileToDelete.exists()) {
            int intFileCount = 0;
            File[] fileSubList = fileToDelete.listFiles();
            intFileCount = fileSubList.length;

            for (int i = 0; i < intFileCount; i++) {
                if (fileSubList[i].isDirectory()) {
                    isDeleteSuccess = deleteDirectory(fileSubList[i].getAbsolutePath());
                } else {
                    isDeleteSuccess = fileSubList[i].delete();
                }
            }
        }

        return isDeleteSuccess;
    }

    public boolean deleteFile(String pLocalPath) {
        boolean isDeleteSuccess = false;

        File fileToDelete = new File(pLocalPath);

        if (fileToDelete.exists()) {
            if (fileToDelete.isFile()) {
                isDeleteSuccess = fileToDelete.delete();
            }
        }

        return isDeleteSuccess;
    }

    public String getFileFullName(String strFilePath) {
        File file = new File(strFilePath);

        return file.getName();
    }

    public String getFileExt(String strFilePath) {
        String ext = "";
        int i = strFilePath.lastIndexOf(".");
        if (i > 0 && i < strFilePath.length() - 1) {
            ext = strFilePath.substring(i + 1).toLowerCase();
        }

        return ext;
    }

    public String getFileName(String strFilePath) {
        String ext = "";
        int i = strFilePath.lastIndexOf(".");
        if (i > 0 && i < strFilePath.length() - 1) {
            ext = strFilePath.substring(0, i).toLowerCase();
        } else {
            ext = strFilePath;
        }

        return ext;
    }
    // Directory & File Handling
    // --------------------------------------------------

    // --------------------------------------------------
    // Getter
    public String getBaseUrl() {
        return mHttpProtocol + "://" + mHttpHost
                + (mHttpPort.equalsIgnoreCase("80") || mHttpPort.equalsIgnoreCase("443") ? "" : ":" + mHttpPort);
    }

    public List<Cookie> getCookies() {
        List<Cookie> listCookie = mCookieStore.getCookies();

        return listCookie;
    }

    public boolean isAnonymous() {
        return mIsAnonymous;
    }

    public boolean isDomino() {
        return mIsDomino;
    }

    public String getHttpHost() {
        return mHttpHost;
    }

    public String getHttpLoginURL() {
        return mHttpLoginURL;
    }

    public String getHttpLogoutURL() {
        return mHttpLogoutURL;
    }

    public String getHttpPort() {
        return mHttpPort;
    }

    public String getHttpProtocol() {
        return mHttpProtocol;
    }

    public String getHttpStatus() {
        return mHttpStatus;
    }

    public String getHttpUserID() {
        return mHttpUserID;
    }

    public String getHttpUserPassword() {
        return mHttpUserPassword;
    }

    public String getLTPAToken() {
        return mLTPAToken;
    }

    public String getMimeType(String pFilePath) {
        String strMimeType = "";
//        MagicMatch match = null;
//
//        try {
////            match = Magic.getMagicMatch(new File(pFilePath), true);
//
//            strMimeType = match.getMimeType();
////        } catch (MagicParseException e) {
////            e.printStackTrace();
////        } catch (MagicMatchNotFoundException e) {
////            e.printStackTrace();
////        } catch (MagicException e) {
////            e.printStackTrace();
//        }

        return strMimeType;
    }

    public String getRedirectedUrl() {
        return mHttpRedirectedUrl;
    }

    public String getRequestedUrl() {
        return sRequestedUrl;
    }

    // Getter
    // --------------------------------------------------

    // --------------------------------------------------
    // Setter
    public void isAnonymous(boolean mIsAnonymous) {
        this.mIsAnonymous = mIsAnonymous;
    }

    public void isDomino(boolean mIsDomino) {
        this.mIsDomino = mIsDomino;
    }

    public void setHttpHost(String mHttpHost) {
        this.mHttpHost = mHttpHost;
    }

    public void setHttpLoginURL(String mHttpLoginURL) {
        this.mHttpLoginURL = mHttpLoginURL;
    }

    public void setHttpLogoutURL(String mHttpLogoutURL) {
        this.mHttpLogoutURL = mHttpLogoutURL;
    }

    public void setHttpPort(String mHttpPort) {
        this.mHttpPort = mHttpPort;
    }

    public void setHttpProtocol(String mHttpProtocol) {
        this.mHttpProtocol = mHttpProtocol;

        if (this.mHttpPort.equalsIgnoreCase("")) {
            if (mHttpProtocol.equalsIgnoreCase("http")) {
                this.mHttpPort = "80";
            } else if (mHttpProtocol.equalsIgnoreCase("https")) {
                this.mHttpPort = "443";
            }
        }
    }

    public void setHttpUserID(String mHttpUserID) {
        this.mHttpUserID = mHttpUserID;
    }

    public void setHttpUserPassword(String mHttpPassword) {
        this.mHttpUserPassword = mHttpPassword;
    }

    public void addLoginData(String pKey, String pValue) {
        if (mHttpDataForRequestLogin == null) {
            mHttpDataForRequestLogin = new ArrayList<BasicNameValuePair>();
        }

        mHttpDataForRequestLogin.add(new BasicNameValuePair(pKey, pValue));
    }

    public void addRequestFile(String sFieldName, File oFile) {
        multipartBuilder = initializeMultipart(multipartBuilder);

        if (mHttpDataForRequestPost != null) {
            if (!mHttpDataForRequestPost.isEmpty()) {
                int iSizeData = mHttpDataForRequestPost.size();
                for (int i = 0; i < iSizeData; i++) {
                    BasicNameValuePair pair = mHttpDataForRequestPost.get(i);

                    multipartBuilder.addTextBody(pair.getName(), pair.getValue(),
                            ContentType.create("multipart/related", "UTF-8"));
                }

                for (int i = 0; i < iSizeData; i++) {
                    mHttpDataForRequestPost.remove(0);
                }
            }
        }

        multipartBuilder.addPart(sFieldName,
                new FileBody(oFile, ContentType.create("application/octet-stream", "UTF-8"), oFile.getName()));
    }

    public void addRequestFile(String sFieldName, String pFilePath) {
        multipartBuilder = initializeMultipart(multipartBuilder);

        if (mHttpDataForRequestPost != null) {
            if (!mHttpDataForRequestPost.isEmpty()) {
                int iSizeData = mHttpDataForRequestPost.size();

                for (int i = 0; i < iSizeData; i++) {
                    BasicNameValuePair pair = mHttpDataForRequestPost.get(i);

                    multipartBuilder.addTextBody(pair.getName(), pair.getValue(),
                            ContentType.create("multipart/related", "UTF-8"));

                }

                for (int i = 0; i < iSizeData; i++) {
                    mHttpDataForRequestPost.remove(0);
                }
            }
        }

        if (mIsDomino) {
            sFieldName = "%%File." + UUID.randomUUID().toString().replaceAll("-", "") + ".$Body";
        }

        multipartBuilder.addPart(sFieldName,
                new FileBody(new File(pFilePath), ContentType.APPLICATION_OCTET_STREAM, getFileFullName(pFilePath)));

    }

    public void addRequestData(String pFieldName, String pFieldValue) {
        if (mHttpDataForRequestPost == null) {
            mHttpDataForRequestPost = new ArrayList<BasicNameValuePair>();

            if (mIsDomino) {
                mHttpDataForRequestPost.add(new BasicNameValuePair("__click", "0"));
            }

            mHttpDataForRequestPost.add(new BasicNameValuePair(pFieldName, pFieldValue));
        } else {
            if (!mHttpDataForRequestPost.isEmpty()) {
                mHttpDataForRequestPost.add(new BasicNameValuePair(pFieldName, pFieldValue));
            } else {
                multipartBuilder = initializeMultipart(multipartBuilder);

                multipartBuilder.addTextBody(pFieldName, pFieldValue, ContentType.create("multipart/related", "UTF-8"));
            }
        }
    }

    public void setRequestJson(String sJsonValue) {
        if (entityBuilder == null) {
            entityBuilder = EntityBuilder.create();
        }

        entityBuilder.setText(sJsonValue);
    }
    // Setter
    // --------------------------------------------------

    // --------------------------------------------------
    // Method
    public void initialize() {
        // --------------------------------------------------
        // SSL
        SSLContext sslContext = null;
        SSLConnectionSocketFactory sslConnectionSocketFactory = null;
        try {
            sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();

            sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext);
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        // --------------------------------------------------

        globalConfig = RequestConfig.custom().setCookieSpec("standard").setSocketTimeout(20000).setConnectTimeout(5000)
                .setConnectionRequestTimeout(5000).build();

        mCookieStore = new BasicCookieStore();

        mHttpClientContext = HttpClientContext.create();
        mHttpClientContext.setCookieStore(mCookieStore);
        mHttpClientContext.setRequestConfig(globalConfig);

        // mHttpClient = HttpClients.custom().setDefaultCookieStore(mCookieStore).setDefaultRequestConfig(globalConfig)
        // .build();

        mHttpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory)
                .setDefaultCookieStore(mCookieStore).setDefaultRequestConfig(globalConfig).build();

        if (mIsDomino)

        {
            addLoginData("__click", "0");
            addLoginData("username", mHttpUserID);
            addLoginData("password", mHttpUserPassword);
        }
    }

    private MultipartEntityBuilder initializeMultipart(MultipartEntityBuilder multipartEntityBuilder) {
        if (multipartEntityBuilder == null) {
            multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            multipartEntityBuilder.setBoundary(boundryKey);
            multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
        }

        return multipartEntityBuilder;
    }

    public String getData(String pRemoteUrl) {
        return getData("UTF-8", pRemoteUrl);
    }

    public String getData(String pEncCode, String pRemoteUrl) {
        String strResultData = "";

        HttpGet httpGet = null;
        CloseableHttpResponse response = null;

        try {
            httpGet = new HttpGet(changeToFullURL(pRemoteUrl));
            httpGet = setBaseHeader(httpGet);

            response = mHttpClient.execute(httpGet, mHttpClientContext);

            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                if (pEncCode.equals(""))
                    strResultData = EntityUtils.toString(entity);
                else {
                    strResultData = EntityUtils.toString(entity, pEncCode);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            httpGet.abort();
        }

        return strResultData.trim();
    }

    public boolean getFile(String pRemoteURL, String strLocalURL) {
        return getFile(pRemoteURL, strLocalURL, false);
    }

    public boolean getFile(String pRemoteUrl, String strLocalUrl, boolean isOverwrite) {
        boolean blnResultData = false;

        FileOutputStream fos = null;
        DataOutputStream dos = null;

        HttpGet httpGet = null;
        CloseableHttpResponse response = null;

        try {
            httpGet = new HttpGet(changeToFullURL(pRemoteUrl));
            httpGet = setBaseHeader(httpGet);

            response = mHttpClient.execute(httpGet, mHttpClientContext);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();

                boolean isDirectoryExist = false;

                String strNewFileName = strLocalUrl;

                File fileLocal = new File(strNewFileName);
                String strDirectoryName = fileLocal.getParent();

                if (!isOverwrite) {
                    int intDupeIncrease = 1;
                    boolean isFinishNewFileCheck = false;

                    String strFileName = getFileName(strNewFileName);
                    String strFileExt = getFileExt(strNewFileName);

                    fileLocal = new File(strNewFileName);
                    strDirectoryName = fileLocal.getParent();

                    if (fileLocal.exists()) {
                        do {
                            strNewFileName = strFileName + " (" + intDupeIncrease + ")" + "." + strFileExt;
                            fileLocal = new File(strNewFileName);

                            if (!fileLocal.exists()) {
                                isFinishNewFileCheck = true;
                            }

                            intDupeIncrease++;
                        } while (!isFinishNewFileCheck);
                    }
                }

                if (strDirectoryName != null) {
                    fileLocal = new File(strDirectoryName);

                    if (fileLocal.exists()) {
                        isDirectoryExist = true;
                    } else {
                        isDirectoryExist = fileLocal.mkdirs();
                    }
                }

                if (isDirectoryExist) {
                    fos = new FileOutputStream(strNewFileName);
                    dos = new DataOutputStream(new BufferedOutputStream(fos));

                    dos.write(EntityUtils.toByteArray(entity));

                    dos.flush();

                    blnResultData = true;
                } else {
                    blnResultData = false;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();

            blnResultData = false;
        } finally {
            try {
                if (fos != null)
                    fos.close();
                if (dos != null)
                    dos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            httpGet.abort();
        }

        return blnResultData;
    }

    public String post(String pURL) {
        return post("UTF-8", pURL);
    }

    public String post(String pEnccode, String pURL) {
        HttpPost httpPost = null;
        HttpResponse response = null;

        String strResData = "";

        try {
            httpPost = new HttpPost(changeToFullURL(pURL));
            httpPost = setBaseHeader(httpPost);


            
            if (mHttpDataForRequestPost == null || mHttpDataForRequestPost.isEmpty()) {
                httpPost.setHeader("Content-Type",
                        ContentType.MULTIPART_FORM_DATA.getMimeType() + ";boundary=" + boundryKey);

                httpPost.setEntity(multipartBuilder.build());
            } else {
                httpPost.setHeader("Content-Type",
                        ContentType.APPLICATION_FORM_URLENCODED.getMimeType() + ";charset=UTF-8");

                if (entityBuilder == null) {
                    httpPost.setEntity(new UrlEncodedFormEntity(mHttpDataForRequestPost, pEnccode));
                } else {
                    httpPost.setEntity(entityBuilder.build());
                }
            }

            response = mHttpClient.execute(httpPost, mHttpClientContext);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
                mHttpRedirectedUrl = response.getFirstHeader("Location").getValue();
            }

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                strResData = EntityUtils.toString(entity);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            httpPost.abort();
        }

        entityBuilder = null;
        multipartBuilder = null;
        mHttpDataForRequestPost = null;

        return strResData;
    }

    public boolean postAndDownload(String pRemoteURL, String strLocalURL) {
        return postAndDownload("UTF-8", pRemoteURL, strLocalURL, false);
    }

    public boolean postAndDownload(String pEnccode, String pRemoteUrl, String strLocalUrl, boolean isOverwrite) {
        boolean blnResultData = false;

        FileOutputStream fos = null;
        DataOutputStream dos = null;

        HttpPost httpPost = null;

        CloseableHttpResponse response = null;

        try {
            httpPost = new HttpPost(changeToFullURL(pRemoteUrl));
            httpPost = setBaseHeader(httpPost);

            if (mHttpDataForRequestPost == null || mHttpDataForRequestPost.isEmpty()) {
                httpPost.setHeader("Content-Type",
                        ContentType.MULTIPART_FORM_DATA.getMimeType() + ";boundary=" + boundryKey);

                httpPost.setEntity(multipartBuilder.build());
            } else {
                httpPost.setHeader("Content-Type",
                        ContentType.APPLICATION_FORM_URLENCODED.getMimeType() + ";charset=UTF-8");

                if (entityBuilder == null) {
                    httpPost.setEntity(new UrlEncodedFormEntity(mHttpDataForRequestPost, pEnccode));
                } else {
                    httpPost.setEntity(entityBuilder.build());
                }
            }

            response = mHttpClient.execute(httpPost, mHttpClientContext);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
                mHttpRedirectedUrl = response.getFirstHeader("Location").getValue();
            }

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();

                boolean isDirectoryExist = false;

                String strNewFileName = strLocalUrl;

                File fileLocal = new File(strNewFileName);
                String strDirectoryName = fileLocal.getParent();

                if (!isOverwrite) {
                    int intDupeIncrease = 1;
                    boolean isFinishNewFileCheck = false;

                    String strFileName = getFileName(strNewFileName);
                    String strFileExt = getFileExt(strNewFileName);

                    fileLocal = new File(strNewFileName);
                    strDirectoryName = fileLocal.getParent();

                    if (fileLocal.exists()) {
                        do {
                            strNewFileName = strFileName + " (" + intDupeIncrease + ")" + "." + strFileExt;
                            fileLocal = new File(strNewFileName);

                            if (!fileLocal.exists()) {
                                isFinishNewFileCheck = true;
                            }

                            intDupeIncrease++;
                        } while (!isFinishNewFileCheck);
                    }
                }

                if (strDirectoryName != null) {
                    fileLocal = new File(strDirectoryName);

                    if (fileLocal.exists()) {
                        isDirectoryExist = true;
                    } else {
                        isDirectoryExist = fileLocal.mkdirs();
                    }
                }

                if (isDirectoryExist) {
                    fos = new FileOutputStream(strNewFileName);
                    dos = new DataOutputStream(new BufferedOutputStream(fos));

                    dos.write(EntityUtils.toByteArray(entity));

                    dos.flush();

                    blnResultData = true;
                } else {
                    blnResultData = false;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null)
                    fos.close();
                if (dos != null)
                    dos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            httpPost.abort();
        }

        entityBuilder = null;
        multipartBuilder = null;
        mHttpDataForRequestPost = null;

        return blnResultData;
    }

    public void requestLogin() {
        mHttpStatus = "";

        if (mIsAnonymous) {
            mHttpStatus = "0";
        } else {
            HttpPost httpPost = null;
            HttpResponse response = null;
            try {
                httpPost = new HttpPost(changeToFullURL(mHttpLoginURL));
                httpPost = setBaseHeader(httpPost);

                try {
                    httpPost.setEntity(new UrlEncodedFormEntity(mHttpDataForRequestLogin, "UTF-8"));
                    response = mHttpClient.execute(httpPost, mHttpClientContext);

                    if (mIsDomino) {
                        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
                            mHttpStatus = "0";
                        } else {
                            mHttpStatus = "200";
                        }
                    } else {
                        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                            mHttpStatus = "0";
                        }
                    }
                } catch (UnsupportedEncodingException e1) {
                    mHttpStatus = "100";
                    logger.error("##### FATAL : {}", e1.getMessage());
                } catch (ClientProtocolException e1) {
                    mHttpStatus = "110";
                    logger.error("##### FATAL : {}", e1.getMessage());
                } catch (IOException e1) {
                    mHttpStatus = "120";
                    logger.error("##### FATAL : {}", e1.getMessage());
                }

                if (mHttpStatus.equals("0")) {
                    List<Cookie> cookies = mCookieStore.getCookies();
                    if (!cookies.isEmpty()) {
                        BasicCookieStore tempCookieStore = new BasicCookieStore();

                        for (int i = 0; i < cookies.size(); i++) {
                            BasicClientCookie cookie = new BasicClientCookie(cookies.get(i).getName(),
                                    cookies.get(i).getValue());

                            cookie.setDomain(mHttpHost);
                            cookie.setPath(cookies.get(i).getPath());

                            if (cookies.get(i).getExpiryDate() != null) {
                                cookie.setExpiryDate(cookies.get(i).getExpiryDate());
                            } else {
                                //???cookie.setExpiryDate(DateUtils.addHours(Calendar.getInstance().getTime(), 1));
                            }

                            tempCookieStore.addCookie(cookie);
                        }

                        mCookieStore.clear();
                        for (Cookie cookie : tempCookieStore.getCookies()) {
                            mCookieStore.addCookie(cookie);
                        }

                        mHttpClientContext.setAttribute(HttpClientContext.COOKIE_STORE, mCookieStore);
                    }
                }
            } finally {
                httpPost.abort();
            }
        }

        entityBuilder = null;
        multipartBuilder = null;
        mHttpDataForRequestPost = null;
    }

    public void requestLogout() {
        if (!mIsAnonymous) {
            try {
                HttpGet httpGet = new HttpGet(changeToFullURL(mHttpLogoutURL));

                mHttpClient.execute(httpGet, mHttpClientContext);
            } catch (IOException e) {
                // e.printStackTrace();
            }
        }

        entityBuilder = null;
        multipartBuilder = null;
        mHttpDataForRequestPost = null;

        mHttpStatus = "";
    }

    private HttpGet setBaseHeader(HttpGet httpGet) {
        httpGet.setHeader("Accept", "text/html, application/xhtml+xml, */*");
        httpGet.setHeader("Accept-Encoding", "gzip, deflate");
        httpGet.setHeader("Accept-Language", "ko-KR");
        httpGet.setHeader("Cache-Control", "no-cache");
        httpGet.setHeader("Connection", "Keep-Alive");
        httpGet.setHeader("Host", mHttpHost
                + (mHttpPort.equalsIgnoreCase("80") || mHttpPort.equalsIgnoreCase("443") ? "" : ":" + mHttpPort));
        httpGet.setHeader("Referer", getRequestedUrl());
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko");

        httpGet.addHeader("X-KNU-API-KEY", "lJwJUyM9tqxdIISEUndJVmNIydwSAKn1");
        httpGet.addHeader("X-KNU-USER-ID", "moumi.web");

        return httpGet;
    }

    private HttpPost setBaseHeader(HttpPost httpPost) {
        httpPost.setHeader("Accept", "text/html, application/xhtml+xml, */*");
        httpPost.setHeader("Accept-Encoding", "gzip, deflate");
        httpPost.setHeader("Accept-Language", "ko-KR");
        httpPost.setHeader("Cache-Control", "no-cache");
        httpPost.setHeader("Connection", "Keep-Alive");
        httpPost.setHeader("Host", mHttpHost
                + (mHttpPort.equalsIgnoreCase("80") || mHttpPort.equalsIgnoreCase("443") ? "" : ":" + mHttpPort));
        httpPost.setHeader("Referer", getRequestedUrl());
        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko");

        httpPost.addHeader("X-KNU-API-KEY", "lJwJUyM9tqxdIISEUndJVmNIydwSAKn1");
        httpPost.addHeader("X-KNU-USER-ID", "moumi.web");
        
        return httpPost;
    }
    // Method
    // --------------------------------------------------

}
