翰林优商.apk(点击下载) / AbstractAjaxCallback.java


package com.androidquery.callback;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.util.Xml;
import android.view.View;
import com.androidquery.auth.AccountHandle;
import com.androidquery.auth.GoogleHandle;
import com.androidquery.util.AQUtility;
import com.androidquery.util.Common;
import com.androidquery.util.Constants;
import com.androidquery.util.PredefinedBAOS;
import com.androidquery.util.Progress;
import com.androidquery.util.XmlDom;
import com.baidu.mobads.sdk.internal.ae;
import com.sigmob.sdk.base.mta.PointCategory;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.xmlpull.v1.XmlPullParser;

public abstract class AbstractAjaxCallback<T, K> implements Runnable {
    private static String AGENT = null;
    private static final Class<?>[] DEFAULT_SIG = {String.class, Object.class, AjaxStatus.class};
    private static boolean GZIP = true;
    private static int NETWORK_POOL = 4;
    private static int NET_TIMEOUT = 30000;
    private static boolean REUSE_CLIENT = true;
    private static boolean SIMULATE_ERROR = false;
    private static final String boundary = "*****";
    private static DefaultHttpClient client = null;
    private static ExecutorService fetchExe = null;
    private static int lastStatus = 200;
    private static final String lineEnd = "\r\n";
    private static ProxyHandle proxyHandle = null;
    private static SocketFactory ssf = null;
    private static Transformer st = null;
    private static final String twoHyphens = "--";
    private boolean abort;
    private WeakReference<Activity> act;
    protected AccountHandle ah;
    private boolean blocked;
    private File cacheDir;
    private String callback;
    private boolean completed;
    protected Map<String, String> cookies;
    private String encoding = "UTF-8";
    private long expire;
    protected boolean fileCache;
    private Object handler;
    protected Map<String, String> headers;
    protected boolean memCache;
    private int method = 4;
    private String networkUrl;
    protected Map<String, Object> params;
    private int policy = 0;
    private WeakReference<Object> progress;
    private HttpHost proxy;
    private boolean reauth;
    private boolean redirect = true;
    private boolean refresh;
    private HttpUriRequest request;
    protected T result;
    private int retry = 0;
    protected AjaxStatus status;
    private File targetFile;
    private int timeout = 0;
    private Transformer transformer;
    private Class<T> type;
    private boolean uiCallback = true;
    private String url;
    private Reference<Object> whandler;

    /* JADX DEBUG: Multi-variable search result rejected for r0v0, resolved type: com.androidquery.callback.AbstractAjaxCallback<T, K> */
    /* JADX WARN: Multi-variable type inference failed */
    private K self() {
        return this;
    }

    public void callback(String str, T t, AjaxStatus ajaxStatus) {
    }

    /* access modifiers changed from: protected */
    public T datastoreGet(String str) {
        return null;
    }

    /* access modifiers changed from: protected */
    public T memGet(String str) {
        return null;
    }

    /* access modifiers changed from: protected */
    public void memPut(String str, T t) {
    }

    /* access modifiers changed from: protected */
    public void skip(String str, T t, AjaxStatus ajaxStatus) {
    }

    private void clear() {
        this.whandler = null;
        this.handler = null;
        this.progress = null;
        this.request = null;
        this.transformer = null;
        this.ah = null;
        this.act = null;
    }

    public static void setTimeout(int i) {
        NET_TIMEOUT = i;
    }

    public static void setAgent(String str) {
        AGENT = str;
    }

    public static void setGZip(boolean z) {
        GZIP = z;
    }

    public static void setSimulateError(boolean z) {
        SIMULATE_ERROR = z;
    }

    public static void setTransformer(Transformer transformer2) {
        st = transformer2;
    }

    public Class<T> getType() {
        return this.type;
    }

    public K weakHandler(Object obj, String str) {
        this.whandler = new WeakReference(obj);
        this.callback = str;
        this.handler = null;
        return self();
    }

    public K handler(Object obj, String str) {
        this.handler = obj;
        this.callback = str;
        this.whandler = null;
        return self();
    }

    public K url(String str) {
        this.url = str;
        return self();
    }

    public K networkUrl(String str) {
        this.networkUrl = str;
        return self();
    }

    public K type(Class<T> cls) {
        this.type = cls;
        return self();
    }

    public K method(int i) {
        this.method = i;
        return self();
    }

    public K timeout(int i) {
        this.timeout = i;
        return self();
    }

    public K redirect(boolean z) {
        this.redirect = z;
        return self();
    }

    public K retry(int i) {
        this.retry = i;
        return self();
    }

    public K transformer(Transformer transformer2) {
        this.transformer = transformer2;
        return self();
    }

    public K fileCache(boolean z) {
        this.fileCache = z;
        return self();
    }

    public K memCache(boolean z) {
        this.memCache = z;
        return self();
    }

    public K policy(int i) {
        this.policy = i;
        return self();
    }

    public K refresh(boolean z) {
        this.refresh = z;
        return self();
    }

    public K uiCallback(boolean z) {
        this.uiCallback = z;
        return self();
    }

    public K expire(long j) {
        this.expire = j;
        return self();
    }

    public K header(String str, String str2) {
        if (this.headers == null) {
            this.headers = new HashMap();
        }
        this.headers.put(str, str2);
        return self();
    }

    public K headers(Map<String, String> map) {
        this.headers = map;
        return self();
    }

    public K cookie(String str, String str2) {
        if (this.cookies == null) {
            this.cookies = new HashMap();
        }
        this.cookies.put(str, str2);
        return self();
    }

    public K cookies(Map<String, String> map) {
        this.cookies = map;
        return self();
    }

    public K encoding(String str) {
        this.encoding = str;
        return self();
    }

    public K proxy(String str, int i) {
        this.proxy = new HttpHost(str, i);
        return self();
    }

    public K proxy(String str, int i, String str2, String str3) {
        proxy(str, i);
        String makeAuthHeader = makeAuthHeader(str2, str3);
        AQUtility.debug("proxy auth", makeAuthHeader);
        return header("Proxy-Authorization", makeAuthHeader);
    }

    private static String makeAuthHeader(String str, String str2) {
        byte[] bytes = (String.valueOf(str) + ":" + str2).getBytes();
        return "Basic " + new String(AQUtility.encode64(bytes, 0, bytes.length));
    }

    public K targetFile(File file) {
        this.targetFile = file;
        return self();
    }

    public K param(String str, Object obj) {
        if (this.params == null) {
            this.params = new HashMap();
        }
        this.params.put(str, obj);
        return self();
    }

    public K params(Map<String, ?> map) {
        this.params = map;
        return self();
    }

    public K progress(View view) {
        return progress((Object) view);
    }

    public K progress(Dialog dialog) {
        return progress((Object) dialog);
    }

    public K progress(Object obj) {
        if (obj != null) {
            this.progress = new WeakReference<>(obj);
        }
        return self();
    }

    /* access modifiers changed from: package-private */
    public void callback() {
        showProgress(false);
        this.completed = true;
        if (!isActive()) {
            skip(this.url, this.result, this.status);
        } else if (this.callback != null) {
            Object handler2 = getHandler();
            Class[] clsArr = {String.class, this.type, AjaxStatus.class};
            AQUtility.invokeHandler(handler2, this.callback, true, true, clsArr, DEFAULT_SIG, this.url, this.result, this.status);
        } else {
            try {
                callback(this.url, this.result, this.status);
            } catch (Exception e) {
                AQUtility.report(e);
            }
        }
        filePut();
        if (!this.blocked) {
            this.status.close();
        }
        wake();
        AQUtility.debugNotify();
    }

    /* JADX WARNING: Exception block dominator not found, dom blocks: [] */
    /* JADX WARNING: Missing exception handler attribute for start block: B:7:0x000c */
    private void wake() {
        if (this.blocked) {
            synchronized (this) {
                notifyAll();
            }
        }
    }

    public void block() {
        if (AQUtility.isUIThread()) {
            throw new IllegalStateException("Cannot block UI thread.");
        } else if (!this.completed) {
            try {
                synchronized (this) {
                    this.blocked = true;
                    wait((long) (NET_TIMEOUT + 5000));
                }
            } catch (Exception unused) {
            }
        }
    }

    /* access modifiers changed from: protected */
    public T fileGet(String str, File file, AjaxStatus ajaxStatus) {
        byte[] bArr;
        try {
            if (isStreamingContent()) {
                ajaxStatus.file(file);
                bArr = null;
            } else {
                bArr = AQUtility.toBytes(new FileInputStream(file));
            }
            return transform(str, bArr, ajaxStatus);
        } catch (Exception e) {
            AQUtility.debug((Throwable) e);
            return null;
        }
    }

    /* access modifiers changed from: protected */
    public void showProgress(final boolean z) {
        WeakReference<Object> weakReference = this.progress;
        final Object obj = weakReference == null ? null : weakReference.get();
        if (obj == null) {
            return;
        }
        if (AQUtility.isUIThread()) {
            Common.showProgress(obj, this.url, z);
        } else {
            AQUtility.post(new Runnable() {
                /* class com.androidquery.callback.AbstractAjaxCallback.AnonymousClass1 */

                public void run() {
                    Common.showProgress(obj, AbstractAjaxCallback.this.url, z);
                }
            });
        }
    }

    /* JADX DEBUG: Multi-variable search result rejected for r10v0, resolved type: byte[] */
    /* JADX WARN: Multi-variable type inference failed */
    /* access modifiers changed from: protected */
    public T transform(String str, byte[] bArr, AjaxStatus ajaxStatus) {
        Exception e;
        String str2;
        if (this.type == null) {
            return null;
        }
        T t = (T) ajaxStatus.getFile();
        if (bArr != 0) {
            if (this.type.equals(Bitmap.class)) {
                return (T) BitmapFactory.decodeByteArray(bArr, 0, bArr.length);
            }
            if (this.type.equals(JSONObject.class)) {
                try {
                    str2 = new String(bArr, this.encoding);
                    try {
                        return (T) ((JSONObject) new JSONTokener(str2).nextValue());
                    } catch (Exception e2) {
                        e = e2;
                        AQUtility.debug((Throwable) e);
                        AQUtility.debug(str2);
                        return null;
                    }
                } catch (Exception e3) {
                    e = e3;
                    str2 = null;
                    AQUtility.debug((Throwable) e);
                    AQUtility.debug(str2);
                    return null;
                }
            } else if (this.type.equals(JSONArray.class)) {
                try {
                    return (T) ((JSONArray) new JSONTokener(new String(bArr, this.encoding)).nextValue());
                } catch (Exception e4) {
                    AQUtility.debug((Throwable) e4);
                    return null;
                }
            } else if (this.type.equals(String.class)) {
                if (ajaxStatus.getSource() == 1) {
                    AQUtility.debug(PointCategory.NETWORK);
                    return (T) correctEncoding(bArr, this.encoding, ajaxStatus);
                }
                AQUtility.debug("file");
                try {
                    return (T) new String(bArr, this.encoding);
                } catch (Exception e5) {
                    AQUtility.debug((Throwable) e5);
                    return null;
                }
            } else if (this.type.equals(byte[].class)) {
                return bArr;
            } else {
                Transformer transformer2 = this.transformer;
                if (transformer2 != null) {
                    return (T) transformer2.transform(str, this.type, this.encoding, bArr, ajaxStatus);
                }
                Transformer transformer3 = st;
                if (transformer3 != null) {
                    return (T) transformer3.transform(str, this.type, this.encoding, bArr, ajaxStatus);
                }
            }
        } else if (t != null) {
            if (this.type.equals(File.class)) {
                return t;
            }
            if (this.type.equals(XmlDom.class)) {
                try {
                    FileInputStream fileInputStream = new FileInputStream((File) t);
                    T t2 = (T) new XmlDom(fileInputStream);
                    ajaxStatus.closeLater(fileInputStream);
                    return t2;
                } catch (Exception e6) {
                    AQUtility.report(e6);
                    return null;
                }
            } else if (this.type.equals(XmlPullParser.class)) {
                T t3 = (T) Xml.newPullParser();
                try {
                    FileInputStream fileInputStream2 = new FileInputStream((File) t);
                    t3.setInput(fileInputStream2, this.encoding);
                    ajaxStatus.closeLater(fileInputStream2);
                    return t3;
                } catch (Exception e7) {
                    AQUtility.report(e7);
                    return null;
                }
            } else if (this.type.equals(InputStream.class)) {
                try {
                    T t4 = (T) new FileInputStream((File) t);
                    ajaxStatus.closeLater(t4);
                    return t4;
                } catch (Exception e8) {
                    AQUtility.report(e8);
                }
            }
        }
        return null;
    }

    private String getCharset(String str) {
        Matcher matcher = Pattern.compile("<meta [^>]*http-equiv[^>]*\"Content-Type\"[^>]*>", 2).matcher(str);
        if (!matcher.find()) {
            return null;
        }
        return parseCharset(matcher.group());
    }

    private String parseCharset(String str) {
        int indexOf;
        if (str == null || (indexOf = str.indexOf("charset")) == -1) {
            return null;
        }
        int indexOf2 = str.indexOf(";", indexOf);
        if (indexOf2 == -1) {
            indexOf2 = str.length();
        }
        return str.substring(indexOf + 7, indexOf2).replaceAll("[^\\w-]", "");
    }

    private String correctEncoding(byte[] bArr, String str, AjaxStatus ajaxStatus) {
        Exception e;
        String str2 = null;
        try {
            if (!"utf-8".equalsIgnoreCase(str)) {
                return new String(bArr, str);
            }
            String parseCharset = parseCharset(ajaxStatus.getHeader("Content-Type"));
            AQUtility.debug("parsing header", parseCharset);
            if (parseCharset != null) {
                return new String(bArr, parseCharset);
            }
            String str3 = new String(bArr, "utf-8");
            try {
                String charset = getCharset(str3);
                AQUtility.debug("parsing needed", charset);
                if (charset == null || "utf-8".equalsIgnoreCase(charset)) {
                    return str3;
                }
                AQUtility.debug("correction needed", charset);
                String str4 = new String(bArr, charset);
                try {
                    ajaxStatus.data(str4.getBytes("utf-8"));
                    return str4;
                } catch (Exception e2) {
                    e = e2;
                    str2 = str4;
                    AQUtility.report(e);
                    return str2;
                }
            } catch (Exception e3) {
                e = e3;
                str2 = str3;
                AQUtility.report(e);
                return str2;
            }
        } catch (Exception e4) {
            e = e4;
            AQUtility.report(e);
            return str2;
        }
    }

    /* access modifiers changed from: protected */
    public void filePut(String str, T t, File file, byte[] bArr) {
        if (file != null && bArr != null) {
            AQUtility.storeAsync(file, bArr, 0);
        }
    }

    /* access modifiers changed from: protected */
    public File accessFile(File file, String str) {
        if (this.expire < 0) {
            return null;
        }
        File existedCacheByUrl = AQUtility.getExistedCacheByUrl(file, str);
        if (existedCacheByUrl == null || this.expire == 0 || System.currentTimeMillis() - existedCacheByUrl.lastModified() <= this.expire) {
            return existedCacheByUrl;
        }
        return null;
    }

    public void async(Activity activity) {
        if (activity.isFinishing()) {
            AQUtility.warn("Warning", "Possible memory leak. Calling ajax with a terminated activity.");
        }
        if (this.type == null) {
            AQUtility.warn("Warning", "type() is not called with response type.");
            return;
        }
        this.act = new WeakReference<>(activity);
        async((Context) activity);
    }

    public void async(Context context) {
        AjaxStatus ajaxStatus = this.status;
        if (ajaxStatus == null) {
            AjaxStatus ajaxStatus2 = new AjaxStatus();
            this.status = ajaxStatus2;
            ajaxStatus2.redirect(this.url).refresh(this.refresh);
        } else if (ajaxStatus.getDone()) {
            this.status.reset();
            this.result = null;
        }
        showProgress(true);
        AccountHandle accountHandle = this.ah;
        if (accountHandle == null || accountHandle.authenticated()) {
            work(context);
            return;
        }
        AQUtility.debug("auth needed", this.url);
        this.ah.auth(this);
    }

    private boolean isActive() {
        WeakReference<Activity> weakReference = this.act;
        if (weakReference == null) {
            return true;
        }
        Activity activity = weakReference.get();
        if (activity == null || activity.isFinishing()) {
            return false;
        }
        return true;
    }

    public void failure(int i, String str) {
        AjaxStatus ajaxStatus = this.status;
        if (ajaxStatus != null) {
            ajaxStatus.code(i).message(str).done();
            if (this.uiCallback) {
                AQUtility.post(this);
            } else {
                afterWork();
            }
        }
    }

    private void work(Context context) {
        T memGet = memGet(this.url);
        if (memGet != null) {
            this.result = memGet;
            this.status.source(4).done();
            callback();
            return;
        }
        this.cacheDir = AQUtility.getCacheDir(context, this.policy);
        execute(this);
    }

    /* access modifiers changed from: protected */
    public boolean cacheAvailable(Context context) {
        return this.fileCache && AQUtility.getExistedCacheByUrl(AQUtility.getCacheDir(context, this.policy), this.url) != null;
    }

    public void run() {
        if (!this.status.getDone()) {
            try {
                backgroundWork();
            } catch (Throwable th) {
                AQUtility.debug(th);
                this.status.code(-101).done();
            }
            if (this.status.getReauth()) {
                return;
            }
            if (this.uiCallback) {
                AQUtility.post(this);
            } else {
                afterWork();
            }
        } else {
            afterWork();
        }
    }

    private void backgroundWork() {
        if (!this.refresh && this.fileCache) {
            fileWork();
        }
        if (this.result == null) {
            datastoreWork();
        }
        if (this.result == null) {
            networkWork();
        }
    }

    private String getCacheUrl() {
        AccountHandle accountHandle = this.ah;
        if (accountHandle != null) {
            return accountHandle.getCacheUrl(this.url);
        }
        return this.url;
    }

    private String getNetworkUrl(String str) {
        String str2 = this.networkUrl;
        if (str2 != null) {
            str = str2;
        }
        AccountHandle accountHandle = this.ah;
        return accountHandle != null ? accountHandle.getNetworkUrl(str) : str;
    }

    private void fileWork() {
        File accessFile = accessFile(this.cacheDir, getCacheUrl());
        if (accessFile != null) {
            this.status.source(3);
            T fileGet = fileGet(this.url, accessFile, this.status);
            this.result = fileGet;
            if (fileGet != null) {
                this.status.time(new Date(accessFile.lastModified())).done();
            }
        }
    }

    private void datastoreWork() {
        T datastoreGet = datastoreGet(this.url);
        this.result = datastoreGet;
        if (datastoreGet != null) {
            this.status.source(2).done();
        }
    }

    private void networkWork() {
        if (this.url == null) {
            this.status.code(-101).done();
            return;
        }
        byte[] bArr = null;
        try {
            network(this.retry + 1);
            AccountHandle accountHandle = this.ah;
            if (accountHandle != null && accountHandle.expired(this, this.status) && !this.reauth) {
                AQUtility.debug("reauth needed", this.status.getMessage());
                this.reauth = true;
                if (this.ah.reauth(this)) {
                    network();
                } else {
                    this.status.reauth(true);
                    return;
                }
            }
            bArr = this.status.getData();
        } catch (IOException e) {
            AQUtility.debug("IOException");
            String message = e.getMessage();
            if (message == null || !message.contains("No authentication challenges found")) {
                this.status.code(-101).message("network error");
            } else {
                this.status.code(401).message(message);
            }
        } catch (Exception e2) {
            AQUtility.debug((Throwable) e2);
            this.status.code(-101).message("network error");
        }
        try {
            this.result = transform(this.url, bArr, this.status);
        } catch (Exception e3) {
            AQUtility.debug((Throwable) e3);
        }
        if (this.result == null && bArr != null) {
            this.status.code(-103).message("transform error");
        }
        lastStatus = this.status.getCode();
        this.status.done();
    }

    /* access modifiers changed from: protected */
    public File getCacheFile() {
        return AQUtility.getCacheFile(this.cacheDir, getCacheUrl());
    }

    /* access modifiers changed from: protected */
    public boolean isStreamingContent() {
        return File.class.equals(this.type) || XmlPullParser.class.equals(this.type) || InputStream.class.equals(this.type) || XmlDom.class.equals(this.type);
    }

    private File getPreFile() {
        File file;
        if (isStreamingContent()) {
            file = this.targetFile;
            if (file == null) {
                if (this.fileCache) {
                    file = getCacheFile();
                } else {
                    File tempDir = AQUtility.getTempDir();
                    if (tempDir == null) {
                        tempDir = this.cacheDir;
                    }
                    file = AQUtility.getCacheFile(tempDir, this.url);
                }
            }
        } else {
            file = null;
        }
        if (file != null && !file.exists()) {
            try {
                file.getParentFile().mkdirs();
                file.createNewFile();
            } catch (Exception e) {
                AQUtility.report(e);
                return null;
            }
        }
        return file;
    }

    private void filePut() {
        if (this.result != null && this.fileCache) {
            byte[] data = this.status.getData();
            if (data != null) {
                try {
                    if (this.status.getSource() == 1) {
                        File cacheFile = getCacheFile();
                        if (!this.status.getInvalid()) {
                            filePut(this.url, this.result, cacheFile, data);
                        } else if (cacheFile.exists()) {
                            cacheFile.delete();
                        }
                    }
                } catch (Exception e) {
                    AQUtility.debug((Throwable) e);
                }
            }
            this.status.data(null);
        } else if (this.status.getCode() == -103) {
            File cacheFile2 = getCacheFile();
            if (cacheFile2.exists()) {
                cacheFile2.delete();
                AQUtility.debug("invalidated cache due to transform error");
            }
        }
    }

    private static String extractUrl(Uri uri) {
        String str = String.valueOf(uri.getScheme()) + "://" + uri.getAuthority() + uri.getPath();
        String fragment = uri.getFragment();
        if (fragment == null) {
            return str;
        }
        return String.valueOf(str) + "#" + fragment;
    }

    /* JADX DEBUG: Multi-variable search result rejected for r0v0, resolved type: java.util.HashMap */
    /* JADX WARN: Multi-variable type inference failed */
    private static Map<String, Object> extractParams(Uri uri) {
        HashMap hashMap = new HashMap();
        for (String str : uri.getQuery().split("&")) {
            String[] split = str.split("=");
            if (split.length >= 2) {
                hashMap.put(split[0], split[1]);
            } else if (split.length == 1) {
                hashMap.put(split[0], "");
            }
        }
        return hashMap;
    }

    private void network(int i) throws IOException {
        if (i <= 1) {
            network();
            return;
        }
        for (int i2 = 0; i2 < i; i2++) {
            try {
                network();
                return;
            } catch (IOException e) {
                if (i2 == i - 1) {
                    throw e;
                }
            }
        }
    }

    private void network() throws IOException {
        String str = this.url;
        Map<String, Object> map = this.params;
        if (map == null && str.length() > 2000) {
            Uri parse = Uri.parse(str);
            String extractUrl = extractUrl(parse);
            map = extractParams(parse);
            str = extractUrl;
        }
        String networkUrl2 = getNetworkUrl(str);
        int i = this.method;
        if (2 == i) {
            httpDelete(networkUrl2, this.status);
        } else if (3 == i) {
            httpPut(networkUrl2, map, this.status);
        } else {
            if (1 == i && map == null) {
                map = new HashMap<>();
            }
            if (map == null) {
                httpGet(networkUrl2, this.status);
            } else if (isMultiPart(map)) {
                httpMulti(networkUrl2, map, this.status);
            } else {
                httpPost(networkUrl2, map, this.status);
            }
        }
    }

    private void afterWork() {
        String str = this.url;
        if (str != null && this.memCache) {
            memPut(str, this.result);
        }
        callback();
        clear();
    }

    public static void execute(Runnable runnable) {
        if (fetchExe == null) {
            fetchExe = Executors.newFixedThreadPool(NETWORK_POOL);
        }
        fetchExe.execute(runnable);
    }

    public static int getActiveCount() {
        ExecutorService executorService = fetchExe;
        if (executorService instanceof ThreadPoolExecutor) {
            return ((ThreadPoolExecutor) executorService).getActiveCount();
        }
        return 0;
    }

    public static void setNetworkLimit(int i) {
        int max = Math.max(1, Math.min(25, i));
        NETWORK_POOL = max;
        fetchExe = null;
        AQUtility.debug("setting network limit", Integer.valueOf(max));
    }

    public static void cancel() {
        ExecutorService executorService = fetchExe;
        if (executorService != null) {
            executorService.shutdownNow();
            fetchExe = null;
        }
        BitmapAjaxCallback.clearTasks();
    }

    private static String patchUrl(String str) {
        return str.replaceAll(" ", "%20").replaceAll("\\|", "%7C");
    }

    private void httpGet(String str, AjaxStatus ajaxStatus) throws IOException {
        AQUtility.debug("get", str);
        String patchUrl = patchUrl(str);
        httpDo(new HttpGet(patchUrl), patchUrl, ajaxStatus);
    }

    private void httpDelete(String str, AjaxStatus ajaxStatus) throws IOException {
        AQUtility.debug("get", str);
        String patchUrl = patchUrl(str);
        httpDo(new HttpDelete(patchUrl), patchUrl, ajaxStatus);
    }

    private void httpPost(String str, Map<String, Object> map, AjaxStatus ajaxStatus) throws ClientProtocolException, IOException {
        AQUtility.debug("post", str);
        httpEntity(str, new HttpPost(str), map, ajaxStatus);
    }

    private void httpPut(String str, Map<String, Object> map, AjaxStatus ajaxStatus) throws ClientProtocolException, IOException {
        AQUtility.debug("put", str);
        httpEntity(str, new HttpPut(str), map, ajaxStatus);
    }

    private void httpEntity(String str, HttpEntityEnclosingRequestBase httpEntityEnclosingRequestBase, Map<String, Object> map, AjaxStatus ajaxStatus) throws ClientProtocolException, IOException {
        HttpEntity httpEntity;
        httpEntityEnclosingRequestBase.getParams().setBooleanParameter("http.protocol.expect-continue", false);
        Object obj = map.get(Constants.POST_ENTITY);
        if (obj instanceof HttpEntity) {
            httpEntity = (HttpEntity) obj;
        } else {
            ArrayList arrayList = new ArrayList();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                Object value = entry.getValue();
                if (value != null) {
                    arrayList.add(new BasicNameValuePair(entry.getKey(), value.toString()));
                }
            }
            httpEntity = new UrlEncodedFormEntity(arrayList, "UTF-8");
        }
        Map<String, String> map2 = this.headers;
        if (map2 != null && !map2.containsKey("Content-Type")) {
            this.headers.put("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        }
        httpEntityEnclosingRequestBase.setEntity(httpEntity);
        httpDo(httpEntityEnclosingRequestBase, str, ajaxStatus);
    }

    public static void setSSF(SocketFactory socketFactory) {
        ssf = socketFactory;
        client = null;
    }

    public static void setReuseHttpClient(boolean z) {
        REUSE_CLIENT = z;
        client = null;
    }

    private static DefaultHttpClient getClient() {
        if (client == null || !REUSE_CLIENT) {
            AQUtility.debug("creating http client");
            BasicHttpParams basicHttpParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(basicHttpParams, NET_TIMEOUT);
            HttpConnectionParams.setSoTimeout(basicHttpParams, NET_TIMEOUT);
            ConnManagerParams.setMaxConnectionsPerRoute(basicHttpParams, new ConnPerRouteBean(25));
            HttpConnectionParams.setSocketBufferSize(basicHttpParams, 8192);
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme(com.czhj.sdk.common.Constants.HTTP, PlainSocketFactory.getSocketFactory(), 80));
            SocketFactory socketFactory = ssf;
            if (socketFactory == null) {
                socketFactory = SSLSocketFactory.getSocketFactory();
            }
            schemeRegistry.register(new Scheme(com.czhj.sdk.common.Constants.HTTPS, socketFactory, 443));
            client = new DefaultHttpClient(new ThreadSafeClientConnManager(basicHttpParams, schemeRegistry), basicHttpParams);
        }
        return client;
    }

    private HttpResponse execute(HttpUriRequest httpUriRequest, DefaultHttpClient defaultHttpClient, HttpContext httpContext) throws ClientProtocolException, IOException {
        HttpHost httpHost;
        if (!httpUriRequest.getURI().getAuthority().contains("_")) {
            return defaultHttpClient.execute(httpUriRequest, httpContext);
        }
        URL url2 = httpUriRequest.getURI().toURL();
        if (url2.getPort() == -1) {
            httpHost = new HttpHost(url2.getHost(), 80, url2.getProtocol());
        } else {
            httpHost = new HttpHost(url2.getHost(), url2.getPort(), url2.getProtocol());
        }
        return defaultHttpClient.execute(httpHost, httpUriRequest, httpContext);
    }

    public static void setProxyHandle(ProxyHandle proxyHandle2) {
        proxyHandle = proxyHandle2;
    }

    /* JADX WARNING: Removed duplicated region for block: B:114:0x01ed  */
    private void httpDo(HttpUriRequest httpUriRequest, String str, AjaxStatus ajaxStatus) throws ClientProtocolException, IOException {
        HttpResponse execute;
        File file;
        String str2;
        String str3;
        InputStream inputStream;
        Throwable th;
        Exception e;
        PredefinedBAOS predefinedBAOS;
        Throwable th2;
        File file2;
        byte[] bArr;
        Map<String, String> map;
        DefaultHttpClient client2 = getClient();
        ProxyHandle proxyHandle2 = proxyHandle;
        if (proxyHandle2 != null) {
            proxyHandle2.applyProxy(this, httpUriRequest, client2);
        }
        String str4 = AGENT;
        if (str4 != null) {
            httpUriRequest.addHeader("User-Agent", str4);
        } else if (str4 == null && GZIP) {
            httpUriRequest.addHeader("User-Agent", "gzip");
        }
        Map<String, String> map2 = this.headers;
        if (map2 != null) {
            for (String str5 : map2.keySet()) {
                httpUriRequest.addHeader(str5, this.headers.get(str5));
            }
        }
        if (GZIP && ((map = this.headers) == null || !map.containsKey("Accept-Encoding"))) {
            httpUriRequest.addHeader("Accept-Encoding", "gzip");
        }
        AccountHandle accountHandle = this.ah;
        if (accountHandle != null) {
            accountHandle.applyToken((AbstractAjaxCallback<?, ?>) this, (HttpRequest) httpUriRequest);
        }
        String makeCookie = makeCookie();
        if (makeCookie != null) {
            httpUriRequest.addHeader("Cookie", makeCookie);
        }
        HttpParams params2 = httpUriRequest.getParams();
        HttpHost httpHost = this.proxy;
        if (httpHost != null) {
            params2.setParameter("http.route.default-proxy", httpHost);
        }
        int i = this.timeout;
        if (i > 0) {
            params2.setParameter("http.connection.timeout", Integer.valueOf(i));
            params2.setParameter("http.socket.timeout", Integer.valueOf(this.timeout));
        }
        if (!this.redirect) {
            params2.setBooleanParameter("http.protocol.handle-redirects", false);
        }
        BasicHttpContext basicHttpContext = new BasicHttpContext();
        basicHttpContext.setAttribute("http.cookie-store", new BasicCookieStore());
        this.request = httpUriRequest;
        if (this.abort) {
            throw new IOException("Aborted");
        } else if (!SIMULATE_ERROR) {
            byte[] bArr2 = null;
            r10 = null;
            InputStream inputStream2 = null;
            InputStream inputStream3 = null;
            try {
                execute = execute(httpUriRequest, client2, basicHttpContext);
            } catch (HttpHostConnectException e2) {
                if (this.proxy != null) {
                    AQUtility.debug("proxy failed, retrying without proxy");
                    params2.setParameter("http.route.default-proxy", null);
                    execute = execute(httpUriRequest, client2, basicHttpContext);
                } else {
                    throw e2;
                }
            }
            int statusCode = execute.getStatusLine().getStatusCode();
            String reasonPhrase = execute.getStatusLine().getReasonPhrase();
            HttpEntity entity = execute.getEntity();
            if (statusCode < 200 || statusCode >= 300) {
                if (entity != null) {
                    try {
                        inputStream = entity.getContent();
                        try {
                            str3 = new String(toData(getEncoding(entity), inputStream), "UTF-8");
                            try {
                                AQUtility.debug("error", str3);
                            } catch (Exception e3) {
                                e = e3;
                            }
                        } catch (Exception e4) {
                            e = e4;
                            str3 = null;
                            try {
                                AQUtility.debug((Throwable) e);
                                AQUtility.close(inputStream);
                                str2 = str;
                                file = null;
                                AQUtility.debug("response", Integer.valueOf(statusCode));
                                if (bArr2 != null) {
                                }
                                ajaxStatus.code(statusCode).message(reasonPhrase).error(str3).redirect(str2).time(new Date()).data(bArr2).file(file).client(client2).context(basicHttpContext).headers(execute.getAllHeaders());
                            } catch (Throwable th3) {
                                th = th3;
                                inputStream3 = inputStream;
                            }
                        }
                    } catch (Exception e5) {
                        e = e5;
                        inputStream = null;
                        str3 = null;
                        AQUtility.debug((Throwable) e);
                        AQUtility.close(inputStream);
                        str2 = str;
                        file = null;
                        AQUtility.debug("response", Integer.valueOf(statusCode));
                        if (bArr2 != null) {
                        }
                        ajaxStatus.code(statusCode).message(reasonPhrase).error(str3).redirect(str2).time(new Date()).data(bArr2).file(file).client(client2).context(basicHttpContext).headers(execute.getAllHeaders());
                    } catch (Throwable th4) {
                        th = th4;
                        AQUtility.close(inputStream3);
                        throw th;
                    }
                } else {
                    inputStream = null;
                    str3 = null;
                }
                AQUtility.close(inputStream);
                str2 = str;
                file = null;
            } else {
                str2 = String.valueOf(((HttpHost) basicHttpContext.getAttribute("http.target_host")).toURI()) + ((HttpUriRequest) basicHttpContext.getAttribute("http.request")).getURI();
                int max = Math.max(32, Math.min(65536, (int) entity.getContentLength()));
                try {
                    file = getPreFile();
                    if (file == null) {
                        predefinedBAOS = new PredefinedBAOS(max);
                        file2 = null;
                    } else {
                        File makeTempFile = makeTempFile(file);
                        file2 = makeTempFile;
                        predefinedBAOS = new BufferedOutputStream(new FileOutputStream(makeTempFile));
                    }
                    try {
                        InputStream content = entity.getContent();
                        try {
                            GZIPInputStream gZIPInputStream = "gzip".equalsIgnoreCase(getEncoding(entity)) ? new GZIPInputStream(content) : content;
                            try {
                                copy(gZIPInputStream, predefinedBAOS, (int) entity.getContentLength(), file2, file);
                                if (file == null) {
                                    bArr = ((PredefinedBAOS) predefinedBAOS).toByteArray();
                                } else if (!file.exists() || file.length() == 0) {
                                    bArr = null;
                                    file = null;
                                } else {
                                    bArr = null;
                                }
                                AQUtility.close(gZIPInputStream);
                                AQUtility.close(predefinedBAOS);
                                str3 = null;
                                bArr2 = bArr;
                            } catch (Throwable th5) {
                                th2 = th5;
                                inputStream2 = gZIPInputStream;
                                AQUtility.close(inputStream2);
                                AQUtility.close(predefinedBAOS);
                                throw th2;
                            }
                        } catch (Throwable th6) {
                            th2 = th6;
                            inputStream2 = content;
                            AQUtility.close(inputStream2);
                            AQUtility.close(predefinedBAOS);
                            throw th2;
                        }
                    } catch (Throwable th7) {
                        th2 = th7;
                        AQUtility.close(inputStream2);
                        AQUtility.close(predefinedBAOS);
                        throw th2;
                    }
                } catch (Throwable th8) {
                    th2 = th8;
                    predefinedBAOS = null;
                    AQUtility.close(inputStream2);
                    AQUtility.close(predefinedBAOS);
                    throw th2;
                }
            }
            AQUtility.debug("response", Integer.valueOf(statusCode));
            if (bArr2 != null) {
                AQUtility.debug(Integer.valueOf(bArr2.length), str);
            }
            ajaxStatus.code(statusCode).message(reasonPhrase).error(str3).redirect(str2).time(new Date()).data(bArr2).file(file).client(client2).context(basicHttpContext).headers(execute.getAllHeaders());
        } else {
            throw new IOException("Simulated Error");
        }
    }

    private String getEncoding(HttpEntity httpEntity) {
        Header contentEncoding;
        if (httpEntity == null || (contentEncoding = httpEntity.getContentEncoding()) == null) {
            return null;
        }
        return contentEncoding.getValue();
    }

    private void copy(InputStream inputStream, OutputStream outputStream, int i, File file, File file2) throws IOException {
        if (file2 == null) {
            copy(inputStream, outputStream, i);
            return;
        }
        try {
            copy(inputStream, outputStream, i);
            inputStream.close();
            outputStream.close();
            file.renameTo(file2);
        } catch (IOException e) {
            AQUtility.debug("copy failed, deleting files");
            file.delete();
            file2.delete();
            AQUtility.close(inputStream);
            AQUtility.close(outputStream);
            throw e;
        }
    }

    private File makeTempFile(File file) throws IOException {
        File file2 = new File(String.valueOf(file.getAbsolutePath()) + ".tmp");
        file2.createNewFile();
        return file2;
    }

    private void copy(InputStream inputStream, OutputStream outputStream, int i) throws IOException {
        WeakReference<Object> weakReference = this.progress;
        Progress progress2 = null;
        Object obj = weakReference != null ? weakReference.get() : null;
        if (obj != null) {
            progress2 = new Progress(obj);
        }
        AQUtility.copy(inputStream, outputStream, i, progress2);
    }

    public K auth(Activity activity, String str, String str2) {
        if (Build.VERSION.SDK_INT >= 5 && str.startsWith("g.")) {
            this.ah = new GoogleHandle(activity, str, str2);
        }
        return self();
    }

    public K auth(AccountHandle accountHandle) {
        this.ah = accountHandle;
        return self();
    }

    public String getUrl() {
        return this.url;
    }

    public Object getHandler() {
        Object obj = this.handler;
        if (obj != null) {
            return obj;
        }
        Reference<Object> reference = this.whandler;
        if (reference == null) {
            return null;
        }
        return reference.get();
    }

    public String getCallback() {
        return this.callback;
    }

    protected static int getLastStatus() {
        return lastStatus;
    }

    public T getResult() {
        return this.result;
    }

    public AjaxStatus getStatus() {
        return this.status;
    }

    public String getEncoding() {
        return this.encoding;
    }

    public void abort() {
        this.abort = true;
        HttpUriRequest httpUriRequest = this.request;
        if (httpUriRequest != null && !httpUriRequest.isAborted()) {
            this.request.abort();
        }
    }

    /* JADX WARNING: Removed duplicated region for block: B:4:0x0010  */
    private static boolean isMultiPart(Map<String, Object> map) {
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            Object value = entry.getValue();
            AQUtility.debug(entry.getKey(), value);
            if ((value instanceof File) || (value instanceof byte[]) || (value instanceof InputStream)) {
                return true;
            }
            while (r2.hasNext()) {
            }
        }
        return false;
    }

    private void httpMulti(String str, Map<String, Object> map, AjaxStatus ajaxStatus) throws IOException {
        Proxy proxy2;
        HttpURLConnection httpURLConnection;
        String str2;
        byte[] bArr;
        AQUtility.debug("multipart", str);
        URL url2 = new URL(str);
        HttpHost httpHost = this.proxy;
        if (httpHost != null) {
            AQUtility.debug("proxy", httpHost);
            proxy2 = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(this.proxy.getHostName(), this.proxy.getPort()));
        } else {
            ProxyHandle proxyHandle2 = proxyHandle;
            proxy2 = proxyHandle2 != null ? proxyHandle2.makeProxy(this) : null;
        }
        if (proxy2 == null) {
            httpURLConnection = (HttpURLConnection) url2.openConnection();
        } else {
            httpURLConnection = (HttpURLConnection) url2.openConnection(proxy2);
        }
        httpURLConnection.setInstanceFollowRedirects(false);
        httpURLConnection.setConnectTimeout(NET_TIMEOUT * 4);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setUseCaches(false);
        httpURLConnection.setRequestMethod(ae.b);
        httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
        httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;charset=utf-8;boundary=*****");
        Map<String, String> map2 = this.headers;
        if (map2 != null) {
            for (String str3 : map2.keySet()) {
                httpURLConnection.setRequestProperty(str3, this.headers.get(str3));
            }
        }
        String makeCookie = makeCookie();
        if (makeCookie != null) {
            httpURLConnection.setRequestProperty("Cookie", makeCookie);
        }
        AccountHandle accountHandle = this.ah;
        if (accountHandle != null) {
            accountHandle.applyToken((AbstractAjaxCallback<?, ?>) this, httpURLConnection);
        }
        DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            writeObject(dataOutputStream, entry.getKey(), entry.getValue());
        }
        dataOutputStream.writeBytes("--*****--\r\n");
        dataOutputStream.flush();
        dataOutputStream.close();
        httpURLConnection.connect();
        int responseCode = httpURLConnection.getResponseCode();
        String responseMessage = httpURLConnection.getResponseMessage();
        String contentEncoding = httpURLConnection.getContentEncoding();
        if (responseCode < 200 || responseCode >= 300) {
            str2 = new String(toData(contentEncoding, httpURLConnection.getErrorStream()), "UTF-8");
            AQUtility.debug("error", str2);
            bArr = null;
        } else {
            bArr = toData(contentEncoding, httpURLConnection.getInputStream());
            str2 = null;
        }
        AQUtility.debug("response", Integer.valueOf(responseCode));
        if (bArr != null) {
            AQUtility.debug(Integer.valueOf(bArr.length), str);
        }
        ajaxStatus.code(responseCode).message(responseMessage).redirect(str).time(new Date()).data(bArr).error(str2).client(null);
    }

    private byte[] toData(String str, InputStream inputStream) throws IOException {
        if ("gzip".equalsIgnoreCase(str)) {
            inputStream = new GZIPInputStream(inputStream);
        }
        return AQUtility.toBytes(inputStream);
    }

    private static void writeObject(DataOutputStream dataOutputStream, String str, Object obj) throws IOException {
        if (obj != null) {
            if (obj instanceof File) {
                File file = (File) obj;
                writeData(dataOutputStream, str, file.getName(), new FileInputStream(file));
            } else if (obj instanceof byte[]) {
                writeData(dataOutputStream, str, str, new ByteArrayInputStream((byte[]) obj));
            } else if (obj instanceof InputStream) {
                writeData(dataOutputStream, str, str, (InputStream) obj);
            } else {
                writeField(dataOutputStream, str, obj.toString());
            }
        }
    }

    private static void writeData(DataOutputStream dataOutputStream, String str, String str2, InputStream inputStream) throws IOException {
        dataOutputStream.writeBytes("--*****\r\n");
        dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + str + "\";" + " filename=\"" + str2 + "\"" + lineEnd);
        dataOutputStream.writeBytes("Content-Type: application/octet-stream");
        dataOutputStream.writeBytes(lineEnd);
        dataOutputStream.writeBytes("Content-Transfer-Encoding: binary");
        dataOutputStream.writeBytes(lineEnd);
        dataOutputStream.writeBytes(lineEnd);
        AQUtility.copy(inputStream, dataOutputStream);
        dataOutputStream.writeBytes(lineEnd);
    }

    private static void writeField(DataOutputStream dataOutputStream, String str, String str2) throws IOException {
        dataOutputStream.writeBytes("--*****\r\n");
        dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + str + "\"");
        dataOutputStream.writeBytes(lineEnd);
        dataOutputStream.writeBytes(lineEnd);
        dataOutputStream.write(str2.getBytes("UTF-8"));
        dataOutputStream.writeBytes(lineEnd);
    }

    private String makeCookie() {
        Map<String, String> map = this.cookies;
        if (map == null || map.size() == 0) {
            return null;
        }
        Iterator<String> it = this.cookies.keySet().iterator();
        StringBuilder sb = new StringBuilder();
        while (it.hasNext()) {
            String next = it.next();
            sb.append(next);
            sb.append("=");
            sb.append(this.cookies.get(next));
            if (it.hasNext()) {
                sb.append("; ");
            }
        }
        return sb.toString();
    }
}