Example usage for org.apache.http.conn ConnectTimeoutException printStackTrace

List of usage examples for org.apache.http.conn ConnectTimeoutException printStackTrace

Introduction

In this page you can find the example usage for org.apache.http.conn ConnectTimeoutException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:CB_Utils.Util.Downloader.java

/**
 * Start downloading the remote resource. The target object should not be accessed until after calling waitUntilCompleted().
 *///ww  w.j a va  2  s  .  c o  m
@Override
public void run() {
    synchronized (stateLock) {
        if (started) {
            return;
        } else {
            started = true;
            running = true;
        }
    }

    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    BufferedReader br = null;

    try {
        /* open connection to the URL */
        checkState();
        progressString = "Opening connection to remote resource";
        progressUpdated = true;

        final URLConnection link;

        try {
            link = url.openConnection();
            link.connect();
        } catch (Exception e) {
            progressString = "Failed to open connection to remote resource";
            progressUpdated = true;
            throw e;
        }

        /* get length of the remote resource */
        checkState();
        progressString = "Getting length of remote resource";
        progressUpdated = true;

        /* get size of webpage in bytes; -1 if unknown */
        final int length = link.getContentLength();

        synchronized (lengthLock) {
            totalLength = length;
        }

        progressUpdated = true;

        /* open input stream to remote resource */
        checkState();
        progressString = "Opening input stream to remote resource";
        progressUpdated = true;

        InputStream input = null;

        try {

            if (totalLength < 1) {

                // load with http Request
                HttpGet httppost = new HttpGet(url.toString());

                // Execute HTTP Post Request
                try {
                    HttpParams httpParameters = new BasicHttpParams();
                    HttpConnectionParams.setConnectionTimeout(httpParameters, HttpUtils.conectionTimeout);
                    HttpConnectionParams.setSoTimeout(httpParameters, HttpUtils.socketTimeout);
                    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
                    HttpResponse response = httpClient.execute(httppost);
                    input = response.getEntity().getContent();
                } catch (ConnectTimeoutException e1) {

                    e1.printStackTrace();
                } catch (ClientProtocolException e1) {

                    e1.printStackTrace();
                } catch (IOException e1) {

                    e1.printStackTrace();
                }

            } else {
                input = link.getInputStream();
            }

            if (target instanceof File) {
                bis = new BufferedInputStream(input);
            } else if (target instanceof StringBuilder) {
                final String contentType = link.getContentType().toLowerCase(Locale.ENGLISH);

                /* look for charset, if specified */
                String charset = null;
                final Matcher m = Pattern.compile(".*charset[\\s]*=([^;]++).*").matcher(contentType);

                if (m.find()) {
                    charset = m.group(1).trim();
                }

                if ((charset != null) && charset.length() > 0) {
                    try {
                        br = new BufferedReader(new InputStreamReader(input, charset));
                    } catch (Exception e) {
                        br = null;
                    }
                }

                if (br == null) {
                    br = new BufferedReader(new InputStreamReader(input));
                }
            }
        } catch (Exception e) {
            progressString = "Failed to open input stream to remote resource";
            progressUpdated = true;
            throw e;
        }

        /* open output stream, if necessary */
        if (target instanceof File) {
            checkState();
            progressString = "Opening output stream to local file";
            progressUpdated = true;

            try {
                /* create parent directories, if necessary */
                final File f = (File) target;
                final File parent = f.getParentFile();

                if ((parent != null) && !parent.exists()) {
                    parent.mkdirs();
                }

                bos = new BufferedOutputStream(f.getFileOutputStream());
            } catch (Exception e) {
                progressString = "Failed to open output stream to local file";
                progressUpdated = true;
                throw e;
            }
        }

        /* download remote resource iteratively */
        progressString = "Downloading";
        progressUpdated = true;

        try {
            if (target instanceof File) {
                final byte[] byteBuffer = new byte[BUFFER_SIZE];

                while (true) {
                    checkState();
                    final int byteCount = bis.read(byteBuffer, 0, BUFFER_SIZE);

                    /* check for end-of-stream */
                    if (byteCount == -1) {
                        break;
                    }

                    bos.write(byteBuffer, 0, byteCount);

                    synchronized (lengthLock) {
                        downloadedLength += byteCount;
                    }

                    progressUpdated = true;
                }
            } else if (target instanceof StringBuilder) {
                final char[] charBuffer = new char[BUFFER_SIZE];
                final StringBuilder sb = (StringBuilder) target;

                while (true) {
                    checkState();
                    final int charCount = br.read(charBuffer, 0, BUFFER_SIZE);

                    /* check for end-of-stream */
                    if (charCount == -1) {
                        break;
                    }

                    sb.append(charBuffer, 0, charCount);

                    synchronized (lengthLock) {
                        downloadedLength += charCount; /* may be inaccurate because byte != char */
                    }

                    progressUpdated = true;
                }
            }
        } catch (Exception e) {
            progressString = "Failed to download remote resource";
            progressUpdated = true;
            throw e;
        }

        /* download completed successfully */
        progressString = "Download completed";
        progressUpdated = true;
    } catch (Exception e) {
        error = e;
    } finally {
        /* clean-up */
        for (Closeable c : new Closeable[] { bis, br, bos }) {
            if (c != null) {
                try {
                    c.close();
                } catch (Exception e) {
                    /* ignore */
                }
            }
        }

        synchronized (stateLock) {
            running = false;
            completed = true;
        }
    }
}

From source file:com.fhc25.percepcion.osiris.mapviewer.common.restutils.RestClient.java

private static void serverConnection(HttpClient client, HttpUriRequest request, RestListener listener) {
    try {//  w  ww.  ja  va 2s . c  o  m
        HttpResponse httpResponse = client.execute(request);
        responseCode = httpResponse.getStatusLine().getStatusCode();
        message = httpResponse.getStatusLine().getReasonPhrase();
        HttpEntity entity = httpResponse.getEntity();

        if (responseCode >= 200 && responseCode <= 299) {
            InputStream isResponse = null;
            if (entity != null) {
                isResponse = entity.getContent();
            }
            listener.onComplete(isResponse);
        } else {
            String errorText = convertStreamToString(entity.getContent());
            Lgr.e(TAG, errorText);
            RestError error = null;
            try {
                error = new RestError(errorText);
            } catch (JSONException je) {
                error = new RestError(-1, 3, "Malformed response");
            }
            listener.onError(error);
        }
        Lgr.v(TAG, "ResponseCode: " + responseCode);
    } catch (ConnectTimeoutException e) {
        Lgr.e(TAG, e.getMessage());
        //e.printStackTrace();
        //listener.onError(new KError(508, 0, e.getMessage()));
        listener.onConnectionFailed();
    } catch (SocketTimeoutException e) {
        Lgr.e(TAG, e.getMessage() + " Socket timeout");
        //e.printStackTrace();
        //listener.onError(new KError(508, 0, "Server timeout"));
        listener.onConnectionFailed();
    } catch (UnknownHostException e) {
        Lgr.e(TAG, e.getMessage() + " Connection failed");
        /*
        KError error = null;
        try {
        error = new KError(e.getMessage());
        } catch (JSONException e1) {
        Lgr.e(TAG, e.getMessage());
        }
        listener.onError(error);
        */

        listener.onConnectionFailed();

    } catch (IOException e) {
        Lgr.e(TAG, e.getMessage());

        RestError error = null;
        try {
            error = new RestError(e.getMessage());
        } catch (JSONException e1) {
            Lgr.e(TAG, e.getMessage());
        }

        listener.onError(error);

    } catch (Exception e) {
        e.printStackTrace();
        listener.onError(new RestError(-1, 0, e.getMessage()));
    }
}

From source file:uk.bowdlerize.service.CensorCensusService.java

private CensorPayload checkURL(String checkURL) throws IllegalArgumentException, URISyntaxException {
    if (!checkURL.startsWith("http"))
        checkURL = "http://" + checkURL;

    CensorPayload censorPayload = new CensorPayload(checkURL);

    Uri mUri = Uri.parse(checkURL);//from www.j  av a2  s. c  o  m

    if (null == mUri.getEncodedQuery()) {
        checkURL = mUri.getScheme() + "://" + mUri.getHost() + mUri.getPath();
    } else {
        checkURL = mUri.getScheme() + "://" + mUri.getHost() + mUri.getPath() + "?"
                + URLEncoder.encode(mUri.getEncodedQuery());
    }

    Log.e("Checking url", checkURL);

    client = new DefaultHttpClient();

    /*headRequest = new HttpHead(checkURL);
    headRequest.setHeader("User-Agent", "OONI Android Probe");*/

    httpGet = new HttpGet(checkURL);
    httpGet.setHeader("User-Agent", "OONI Android Probe");

    try {
        //response = client.execute(headRequest);
        client.addResponseInterceptor(new HttpResponseInterceptor() {
            @Override
            public void process(HttpResponse httpResponse, HttpContext httpContext)
                    throws HttpException, IOException {
                if (httpResponse.getStatusLine().getStatusCode() == 302
                        || httpResponse.getStatusLine().getStatusCode() == 301) {
                    for (Header hdr : httpResponse.getAllHeaders()) {
                        if (hdr.getName().equals("Location")) {
                            /*if (hdr.getValue().equals("http://ee-outage.s3.amazonaws.com/content-blocked/content-blocked-v1.html") ||
                            hdr.getValue().contains("http://ee-outage.s3.amazonaws.com"))
                            {
                            Log.e("Blocked", "Blocked by EE");
                            throw new CensoredException("Blocked by EE", "EE", 100);
                            }
                            else if (hdr.getValue().contains("http://www.t-mobile.co.uk/service/wnw-mig/entry/") ||
                                 hdr.getValue().contains("http://tmobile.ee.co.uk/common/system_error_pages/outage_wnw.html"))
                            {
                            Log.e("Blocked", "Blocked by TMobile");
                            throw new CensoredException("Blocked by TMobile", "TMobile", 100);
                            }
                            else if (hdr.getValue().contains("http://online.vodafone.co.uk/dispatch/Portal/ContentControlServlet?type=restricted"))
                            {
                            Log.e("Blocked", "Blocked by Vodafone");
                            throw new CensoredException("Blocked by Vodafone", "Vodafone", 100);
                            }
                            else if (hdr.getValue().contains("http://blockpage.bt.com/pcstaticpage/blocked.html"))
                            {
                            Log.e("Blocked", "Blocked by BT");
                            throw new CensoredException("Blocked by BT", "BT", 100);
                            }
                            else if (hdr.getValue().contains("http://www.talktalk.co.uk/notice/parental-controls?accessurl"))
                            {
                            Log.e("Blocked", "Blocked by TalkTalk");
                            throw new CensoredException("Blocked by TalkTalk", "TalkTalk", 100);
                            }
                            else if (hdr.getValue().contains("http://www.plus.net/support/security/abuse/blocked.shtml"))
                            {
                            Log.e("Blocked", "Blocked by PlusNet");
                            throw new CensoredException("Blocked by PlusNet", "PlusNet", 100);
                            }
                            else if (hdr.getValue().contains("http://mobile.three.co.uk/pc/Live/pcreator/live/100004/pin/blocked?"))
                            {
                            Log.e("Blocked", "Blocked by Three");
                            throw new CensoredException("Blocked by Three", "Three", 100);
                            }
                            else if (hdr.getValue().contains("http://m.virginmedia.com/MiscPages/AdultWarning.aspx"))
                            {
                            Log.e("Blocked", "Blocked by VirginMobile");
                            throw new CensoredException("Blocked by VirginMobile", "VirginMobile", 100);
                            }
                            else if (hdr.getValue().contains("http://assets.o2.co.uk/18plusaccess/"))
                            {
                            Log.e("Blocked", "Blocked by O2");
                            throw new CensoredException("Blocked by O2", "O2", 100);
                            }*/
                            api.checkHeader(hdr);
                        }
                    }
                }

                /*Log.e("intercepted return code",httpResponse.getStatusLine().toString());
                        
                for(Header hdr : httpResponse.getAllHeaders())
                {
                Log.e("intercepted header",hdr.getName().toString() + " / " + hdr.getValue().toString());
                }
                Log.e("intercepted header","------------------\r\n------------------\r\n------------------\r\n------------------\r\n------------------\r\n");*/

            }
        });
        response = client.execute(httpGet);
    }
    //This is the best case scenario!
    catch (CensoredException CE) {
        censorPayload.consumeCensoredException(CE);
        return censorPayload;
    } catch (UnknownHostException uhe) {
        uhe.printStackTrace();
        censorPayload.consumeError(uhe.getMessage());
        return censorPayload;
    } catch (ConnectTimeoutException CTE) {
        CTE.printStackTrace();
        censorPayload.consumeError(CTE.getMessage());
        return censorPayload;
    } catch (NoHttpResponseException NHRE) {
        NHRE.printStackTrace();
        censorPayload.consumeError(NHRE.getMessage());
        return censorPayload;
    } catch (IOException ioe) {
        ioe.printStackTrace();
        censorPayload.consumeError(ioe.getMessage());
        return censorPayload;
    } catch (IllegalStateException ise) {
        ise.printStackTrace();
        censorPayload.setCensored(false);
        censorPayload.setConfidence(0);
        return censorPayload;
    } catch (Exception e) {
        e.printStackTrace();
        censorPayload.setCensored(false);
        censorPayload.setConfidence(0);
        return censorPayload;
    }

    int statusCode = response.getStatusLine().getStatusCode();

    censorPayload.setReturnCode(statusCode);

    Log.e("checkURL code", Integer.toString(statusCode));
    if (statusCode == 403 || statusCode == 404) {
        censorPayload.setCensored(true);
        censorPayload.setConfidence(25);
        return censorPayload;
    } else if (statusCode == 504 || statusCode == 503 || statusCode == 500) {
        censorPayload.consumeError("Server Issue " + Integer.toString(statusCode));
        return censorPayload;
    }

    String phrase = response.getStatusLine().getReasonPhrase();

    Log.e("checkURL phrase", phrase);

    if (phrase.contains("orbidden")) {
        censorPayload.setCensored(true);
        censorPayload.setConfidence(50);
        return censorPayload;
    }

    if (phrase.contains("blocked")) {
        censorPayload.setCensored(true);
        censorPayload.setConfidence(100);
        return censorPayload;
    }

    for (Header hdr : response.getAllHeaders()) {
        Log.e("checkURL header", hdr.getName() + " / " + hdr.getValue());
    }

    censorPayload.setCensored(false);
    censorPayload.setConfidence(1);
    return censorPayload;
}

From source file:com.mediatek.systemupdate.HttpManager.java

private HttpResponse doPost(String url, Map<String, String> headers, ArrayList<BasicNameValuePair> bnvpa) {

    Xlog.i(TAG, "doPost, url = " + url + ", mCookies = " + mCookies);
    HttpContext localcontext = new BasicHttpContext();
    if (mCookies != null) {
        localcontext.setAttribute(ClientContext.COOKIE_STORE, mCookies);
    }//from w w  w  .j  a v  a2s . c o m
    HttpResponse response = null;
    try {
        HttpHost host = null;
        HttpPost httpPost = null;

        if (url.contains("https")) {
            Uri uri = Uri.parse(url);
            host = new HttpHost(uri.getHost(), PORT_NUMBER, uri.getScheme());
            httpPost = new HttpPost(uri.getPath());
        } else {
            httpPost = new HttpPost(url);
        }

        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpPost.addHeader(entry.getKey(), entry.getValue());
            }
        }

        if (bnvpa != null) {
            httpPost.setEntity(new UrlEncodedFormEntity(bnvpa));
        }
        DefaultHttpClient httpClient = new DefaultHttpClient(mHttpConnMgr, mHttpParam);

        try {
            if (url.contains("https")) {
                Xlog.i(TAG, "doPost, https");
                response = httpClient.execute(host, httpPost);
            } else {
                Xlog.i(TAG, "doPost, http");
                Xlog.i(TAG, "mHttpClient =" + httpClient + "httpPost = " + httpPost + "localcontext = "
                        + localcontext);
                response = httpClient.execute(httpPost, localcontext);
            }
            if (mCookies == null) {
                mCookies = httpClient.getCookieStore();
                Xlog.i(TAG, "mCookies size = " + mCookies.getCookies().size());
            }
            return response;
        } catch (ConnectTimeoutException e) {
            e.printStackTrace();
            mErrorCode = HTTP_RESPONSE_NETWORK_ERROR;
        }

    } catch (UnsupportedEncodingException e) {

        e.printStackTrace();
        mErrorCode = HTTP_RESPONSE_NETWORK_ERROR;
    } catch (IOException e) {
        e.printStackTrace();
        mErrorCode = HTTP_RESPONSE_NETWORK_ERROR;
    }
    return response;
}