package common.util.httpclient.impl;

import common.util.SysLog;
import common.util.httpclient.HttpSendResult;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.net.SocketFactory;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpClientError;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

public class SimpleHttpsClientImpl implements SimpleHttpsClient {
    private static final SysLog logger = SysLog.getLogger(SimpleHttpsClientImpl.class);
    private Map<Integer, Integer> registerPortList = new HashMap();

    public SimpleHttpsClientImpl() {
        Protocol.registerProtocol("https", new Protocol("https", new SimpleHttpsClientImpl.SimpleHttpsSocketFactory(), 443));
        this.registerPort(443);
    }

    public HttpSendResult postRequest(String url, Map<String, String> params, int timeout, String charset) {
        HttpSendResult result = new HttpSendResult();
        PostMethod postMethod = new PostMethod(url);
        NameValuePair[] data = this.createNameValuePair(params);
        postMethod.setRequestBody(data);
        Integer port = this.getPort(url);
        if (this.isRegisterPort(port)) {
            Protocol myhttps = new Protocol("https", new SimpleHttpsClientImpl.SimpleHttpsSocketFactory(), port);
            Protocol.registerProtocol("https ", myhttps);
            this.registerPort(port);
        }

        HttpClient client = new HttpClient();
        client.getParams().setSoTimeout(timeout);
        if (StringUtils.isNotBlank(charset)) {
            client.getParams().setParameter("http.protocol.content-charset", charset);
        }

        try {
            int status = client.executeMethod(postMethod);
            InputStream is = postMethod.getResponseBodyAsStream();
            String responseBody = IOUtils.toString(is, "UTF-8");
            result.setStatus(status);
            result.setResponseBody(responseBody);
        } catch (Exception var16) {
            throw new RuntimeException(var16);
        } finally {
            postMethod.releaseConnection();
        }

        return result;
    }

    public HttpSendResult postRequest(String url, Map<String, String> params, int timeout) {
        return this.postRequest(url, params, timeout, (String)null);
    }

    private String appendUrlString(String url, String getParamString) {
        StringBuilder sb = new StringBuilder();
        sb.append(url);
        if (StringUtils.isNotEmpty(getParamString)) {
            if (url.indexOf("?") != -1 && url.indexOf("=") != -1) {
                sb.append("&");
            } else {
                sb.append("?");
            }

            sb.append(getParamString);
        }

        return sb.toString();
    }

    public HttpSendResult getRequest(String url, String getParamString, int timeout) {
        return this.getRequest(url, getParamString, timeout, false);
    }

    public HttpSendResult getRequest(String url, String getParamString, int timeout, boolean followRedirects) {
        HttpSendResult result = new HttpSendResult();
        Integer port = this.getPort(url);
        if (this.isRegisterPort(port)) {
            Protocol myhttps = new Protocol("https", new SimpleHttpsClientImpl.SimpleHttpsSocketFactory(), port);
            Protocol.registerProtocol("https ", myhttps);
            this.registerPort(port);
        }

        url = this.appendUrlString(url, getParamString);
        HttpClient httpclient = new HttpClient();
        httpclient.getParams().setSoTimeout(timeout);
        GetMethod httpget = new GetMethod(url);

        try {
            httpget.setFollowRedirects(followRedirects);
            int status = httpclient.executeMethod(httpget);
            result.setStatus(status);
            if (status != 301 && status != 302) {
                InputStream is = httpget.getResponseBodyAsStream();
                String responseBody = IOUtils.toString(is, "UTF-8");
                result.setResponseBody(responseBody);
            } else {
                Header locationHeader = httpget.getResponseHeader("location");
                logger.logInfo("location header:" + locationHeader.getValue());
                result.setResponseBody(locationHeader.getValue());
            }
        } catch (Exception var15) {
            throw new RuntimeException(var15);
        } finally {
            httpget.releaseConnection();
        }

        return result;
    }

    private boolean isRegisterPort(Integer port) {
        return this.registerPortList.get(port) != null;
    }

    private void registerPort(Integer port) {
        this.registerPortList.put(port, port);
    }

    private Integer getPort(String uri) {
        try {
            URL url = new URL(uri);
            int port = url.getPort();
            if (port == -1) {
                if (uri.indexOf("https://") == 0) {
                    port = 443;
                } else {
                    port = 80;
                }
            }

            return port;
        } catch (MalformedURLException var4) {
            throw new RuntimeException(var4);
        }
    }

    private NameValuePair[] createNameValuePair(Map<String, String> params) {
        NameValuePair[] pairs = new NameValuePair[params.size()];
        int index = 0;

        String key;
        for(Iterator i$ = params.keySet().iterator(); i$.hasNext(); pairs[index++] = new NameValuePair(key, (String)params.get(key))) {
            key = (String)i$.next();
        }

        return pairs;
    }

    private String appendUrlParam(String url, Map<String, String> params) {
        String result = "";
        if (url.indexOf("?") != -1 && url.indexOf("=") != -1) {
            result = url + "&";
        } else {
            result = url + "?";
        }

        String key;
        for(Iterator i$ = params.keySet().iterator(); i$.hasNext(); result = result + key + "=" + (String)params.get(key) + "&") {
            key = (String)i$.next();
        }

        if (result.charAt(result.length() - 1) == '&') {
            result = result.substring(0, result.length() - 1);
        }

        return result;
    }

    private class SimpleHttpsSocketFactory implements ProtocolSocketFactory {
        private SSLContext sslcontext;

        private SimpleHttpsSocketFactory() {
            this.sslcontext = null;
        }

        private SSLContext createEasySSLContext() {
            try {
                X509TrustManager trustMgr = new X509TrustManager() {
                    public void checkClientTrusted(X509Certificate[] ax509certificate, String s) throws CertificateException {
                    }

                    public void checkServerTrusted(X509Certificate[] ax509certificate, String s) throws CertificateException {
                    }

                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                };
                TrustManager[] trustMgrs = new TrustManager[]{trustMgr};
                SSLContext context = SSLContext.getInstance("SSL");
                context.init((KeyManager[])null, trustMgrs, (SecureRandom)null);
                return context;
            } catch (Exception var4) {
                var4.printStackTrace();
                throw new HttpClientError(var4.toString());
            }
        }

        private SSLContext getSSLContext() {
            if (this.sslcontext == null) {
                this.sslcontext = this.createEasySSLContext();
            }

            return this.sslcontext;
        }

        public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException, UnknownHostException {
            return this.getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort);
        }

        public Socket createSocket(String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
            if (params == null) {
                throw new IllegalArgumentException("Parameters may not be null");
            } else {
                int timeout = params.getConnectionTimeout();
                SocketFactory socketfactory = this.getSSLContext().getSocketFactory();
                if (timeout == 0) {
                    return socketfactory.createSocket(host, port, localAddress, localPort);
                } else {
                    Socket socket = socketfactory.createSocket();
                    SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
                    SocketAddress remoteaddr = new InetSocketAddress(host, port);
                    socket.bind(localaddr);
                    socket.connect(remoteaddr, timeout);
                    return socket;
                }
            }
        }

        public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
            return this.getSSLContext().getSocketFactory().createSocket(host, port);
        }

        public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
            return this.getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose);
        }

        public boolean equals(Object obj) {
            return obj != null && obj.getClass().equals(SSLSocketFactory.class);
        }

        public int hashCode() {
            return SimpleHttpsClientImpl.SimpleHttpsSocketFactory.class.hashCode();
        }
    }
}
