Search in sources :

Example 1 with HttpConnectCallback

use of com.koushikdutta.async.http.callback.HttpConnectCallback in project AndroidAsync by koush.

the class AsyncHttpClient method executeAffinity.

private void executeAffinity(final AsyncHttpRequest request, final int redirectCount, final FutureAsyncHttpResponse cancel, final HttpConnectCallback callback) {
    assert mServer.isAffinityThread();
    if (redirectCount > 15) {
        reportConnectedCompleted(cancel, new RedirectLimitExceededException("too many redirects"), null, request, callback);
        return;
    }
    final Uri uri = request.getUri();
    final AsyncHttpClientMiddleware.OnResponseCompleteDataOnRequestSentData data = new AsyncHttpClientMiddleware.OnResponseCompleteDataOnRequestSentData();
    request.executionTime = System.currentTimeMillis();
    data.request = request;
    request.logd("Executing request.");
    for (AsyncHttpClientMiddleware middleware : mMiddleware) {
        middleware.onRequest(data);
    }
    if (request.getTimeout() > 0) {
        // set connect timeout
        cancel.timeoutRunnable = new Runnable() {

            @Override
            public void run() {
                // we've timed out, kill the connections
                if (data.socketCancellable != null) {
                    data.socketCancellable.cancel();
                    if (data.socket != null)
                        data.socket.close();
                }
                reportConnectedCompleted(cancel, new TimeoutException(), null, request, callback);
            }
        };
        cancel.scheduled = mServer.postDelayed(cancel.timeoutRunnable, getTimeoutRemaining(request));
    }
    // 2) wait for a connect
    data.connectCallback = new ConnectCallback() {

        boolean reported;

        @Override
        public void onConnectCompleted(Exception ex, AsyncSocket socket) {
            if (reported) {
                if (socket != null) {
                    socket.setDataCallback(new DataCallback.NullDataCallback());
                    socket.setEndCallback(new CompletedCallback.NullCompletedCallback());
                    socket.close();
                    throw new AssertionError("double connect callback");
                }
            }
            reported = true;
            request.logv("socket connected");
            if (cancel.isCancelled()) {
                if (socket != null)
                    socket.close();
                return;
            }
            // 3) on connect, cancel timeout
            if (cancel.timeoutRunnable != null)
                mServer.removeAllCallbacks(cancel.scheduled);
            if (ex != null) {
                reportConnectedCompleted(cancel, ex, null, request, callback);
                return;
            }
            data.socket = socket;
            cancel.socket = socket;
            executeSocket(request, redirectCount, cancel, callback, data);
        }
    };
    // set up the system default proxy and connect
    setupAndroidProxy(request);
    // set the implicit content type
    if (request.getBody() != null) {
        if (request.getHeaders().get("Content-Type") == null)
            request.getHeaders().set("Content-Type", request.getBody().getContentType());
    }
    final Exception unsupportedURI;
    for (AsyncHttpClientMiddleware middleware : mMiddleware) {
        Cancellable socketCancellable = middleware.getSocket(data);
        if (socketCancellable != null) {
            data.socketCancellable = socketCancellable;
            cancel.setParent(socketCancellable);
            return;
        }
    }
    unsupportedURI = new IllegalArgumentException("invalid uri=" + request.getUri() + " middlewares=" + mMiddleware);
    reportConnectedCompleted(cancel, unsupportedURI, null, request, callback);
}
Also used : Cancellable(com.koushikdutta.async.future.Cancellable) Uri(android.net.Uri) TimeoutException(java.util.concurrent.TimeoutException) AsyncSSLException(com.koushikdutta.async.AsyncSSLException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) AsyncSocket(com.koushikdutta.async.AsyncSocket) HttpConnectCallback(com.koushikdutta.async.http.callback.HttpConnectCallback) ConnectCallback(com.koushikdutta.async.callback.ConnectCallback) TimeoutException(java.util.concurrent.TimeoutException)

Example 2 with HttpConnectCallback

use of com.koushikdutta.async.http.callback.HttpConnectCallback in project AndroidAsync by koush.

the class AsyncHttpClient method executeFile.

public Future<File> executeFile(AsyncHttpRequest req, final String filename, final FileCallback callback) {
    final File file = new File(filename);
    file.getParentFile().mkdirs();
    final OutputStream fout;
    try {
        fout = new BufferedOutputStream(new FileOutputStream(file), 8192);
    } catch (FileNotFoundException e) {
        SimpleFuture<File> ret = new SimpleFuture<File>();
        ret.setComplete(e);
        return ret;
    }
    final FutureAsyncHttpResponse cancel = new FutureAsyncHttpResponse();
    final SimpleFuture<File> ret = new SimpleFuture<File>() {

        @Override
        public void cancelCleanup() {
            try {
                cancel.get().setDataCallback(new DataCallback.NullDataCallback());
                cancel.get().close();
            } catch (Exception e) {
            }
            try {
                fout.close();
            } catch (Exception e) {
            }
            file.delete();
        }
    };
    ret.setParent(cancel);
    execute(req, 0, cancel, new HttpConnectCallback() {

        long mDownloaded = 0;

        @Override
        public void onConnectCompleted(Exception ex, final AsyncHttpResponse response) {
            if (ex != null) {
                try {
                    fout.close();
                } catch (IOException e) {
                }
                file.delete();
                invoke(callback, ret, response, ex, null);
                return;
            }
            invokeConnect(callback, response);
            final long contentLength = HttpUtil.contentLength(response.headers());
            response.setDataCallback(new OutputStreamDataCallback(fout) {

                @Override
                public void onDataAvailable(DataEmitter emitter, ByteBufferList bb) {
                    mDownloaded += bb.remaining();
                    super.onDataAvailable(emitter, bb);
                    invokeProgress(callback, response, mDownloaded, contentLength);
                }
            });
            response.setEndCallback(new CompletedCallback() {

                @Override
                public void onCompleted(Exception ex) {
                    try {
                        fout.close();
                    } catch (IOException e) {
                        ex = e;
                    }
                    if (ex != null) {
                        file.delete();
                        invoke(callback, ret, response, ex, null);
                    } else {
                        invoke(callback, ret, response, null, file);
                    }
                }
            });
        }
    });
    return ret;
}
Also used : CompletedCallback(com.koushikdutta.async.callback.CompletedCallback) ByteBufferList(com.koushikdutta.async.ByteBufferList) HttpConnectCallback(com.koushikdutta.async.http.callback.HttpConnectCallback) OutputStreamDataCallback(com.koushikdutta.async.stream.OutputStreamDataCallback) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) OutputStreamDataCallback(com.koushikdutta.async.stream.OutputStreamDataCallback) DataCallback(com.koushikdutta.async.callback.DataCallback) TimeoutException(java.util.concurrent.TimeoutException) AsyncSSLException(com.koushikdutta.async.AsyncSSLException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) FileOutputStream(java.io.FileOutputStream) DataEmitter(com.koushikdutta.async.DataEmitter) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream) SimpleFuture(com.koushikdutta.async.future.SimpleFuture)

Example 3 with HttpConnectCallback

use of com.koushikdutta.async.http.callback.HttpConnectCallback in project AndroidAsync by koush.

the class AsyncHttpClient method websocket.

public Future<WebSocket> websocket(final AsyncHttpRequest req, String protocol, final WebSocketConnectCallback callback) {
    WebSocketImpl.addWebSocketUpgradeHeaders(req, protocol);
    final SimpleFuture<WebSocket> ret = new SimpleFuture<WebSocket>();
    Cancellable connect = execute(req, new HttpConnectCallback() {

        @Override
        public void onConnectCompleted(Exception ex, AsyncHttpResponse response) {
            if (ex != null) {
                if (ret.setComplete(ex)) {
                    if (callback != null)
                        callback.onCompleted(ex, null);
                }
                return;
            }
            WebSocket ws = WebSocketImpl.finishHandshake(req.getHeaders(), response);
            if (ws == null) {
                ex = new WebSocketHandshakeException("Unable to complete websocket handshake");
                if (!ret.setComplete(ex))
                    return;
            } else {
                if (!ret.setComplete(ws))
                    return;
            }
            if (callback != null)
                callback.onCompleted(ex, ws);
        }
    });
    ret.setParent(connect);
    return ret;
}
Also used : HttpConnectCallback(com.koushikdutta.async.http.callback.HttpConnectCallback) Cancellable(com.koushikdutta.async.future.Cancellable) TimeoutException(java.util.concurrent.TimeoutException) AsyncSSLException(com.koushikdutta.async.AsyncSSLException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) SimpleFuture(com.koushikdutta.async.future.SimpleFuture)

Example 4 with HttpConnectCallback

use of com.koushikdutta.async.http.callback.HttpConnectCallback in project AndroidAsync by koush.

the class AsyncHttpClient method execute.

public <T> SimpleFuture<T> execute(AsyncHttpRequest req, final AsyncParser<T> parser, final RequestCallback<T> callback) {
    final FutureAsyncHttpResponse cancel = new FutureAsyncHttpResponse();
    final SimpleFuture<T> ret = new SimpleFuture<T>();
    execute(req, 0, cancel, new HttpConnectCallback() {

        @Override
        public void onConnectCompleted(Exception ex, final AsyncHttpResponse response) {
            if (ex != null) {
                invoke(callback, ret, response, ex, null);
                return;
            }
            invokeConnect(callback, response);
            Future<T> parsed = parser.parse(response).setCallback(new FutureCallback<T>() {

                @Override
                public void onCompleted(Exception e, T result) {
                    invoke(callback, ret, response, e, result);
                }
            });
            // reparent to the new parser future
            ret.setParent(parsed);
        }
    });
    ret.setParent(cancel);
    return ret;
}
Also used : HttpConnectCallback(com.koushikdutta.async.http.callback.HttpConnectCallback) SimpleFuture(com.koushikdutta.async.future.SimpleFuture) Future(com.koushikdutta.async.future.Future) TimeoutException(java.util.concurrent.TimeoutException) AsyncSSLException(com.koushikdutta.async.AsyncSSLException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) FutureCallback(com.koushikdutta.async.future.FutureCallback) SimpleFuture(com.koushikdutta.async.future.SimpleFuture)

Example 5 with HttpConnectCallback

use of com.koushikdutta.async.http.callback.HttpConnectCallback in project AndroidAsync by koush.

the class HttpClientTests method testGithubRandomData.

public void testGithubRandomData() throws Exception {
    final Semaphore semaphore = new Semaphore(0);
    final Md5 md5 = Md5.createInstance();
    AsyncHttpGet get = new AsyncHttpGet(github);
    get.setLogging("AsyncTest", Log.VERBOSE);
    client.execute(get, new HttpConnectCallback() {

        @Override
        public void onConnectCompleted(Exception ex, AsyncHttpResponse response) {
            assertNull(ex);
            // make sure gzip decoding works, as that is generally what github sends.
            // this broke sometime in 03/2014
            //                Assert.assertEquals("gzip", response.getHeaders().getContentEncoding());
            response.setDataCallback(new DataCallback() {

                @Override
                public void onDataAvailable(DataEmitter emitter, ByteBufferList bb) {
                    md5.update(bb);
                }
            });
            response.setEndCallback(new CompletedCallback() {

                @Override
                public void onCompleted(Exception ex) {
                    semaphore.release();
                }
            });
        }
    });
    assertTrue("timeout", semaphore.tryAcquire(TIMEOUT, TimeUnit.MILLISECONDS));
    assertEquals(md5.digest(), dataNameAndHash);
}
Also used : AsyncHttpGet(com.koushikdutta.async.http.AsyncHttpGet) CompletedCallback(com.koushikdutta.async.callback.CompletedCallback) AsyncHttpResponse(com.koushikdutta.async.http.AsyncHttpResponse) ByteBufferList(com.koushikdutta.async.ByteBufferList) HttpConnectCallback(com.koushikdutta.async.http.callback.HttpConnectCallback) DataEmitter(com.koushikdutta.async.DataEmitter) Semaphore(java.util.concurrent.Semaphore) DataCallback(com.koushikdutta.async.callback.DataCallback) TimeoutException(java.util.concurrent.TimeoutException) CancellationException(java.util.concurrent.CancellationException) ExecutionException(java.util.concurrent.ExecutionException)

Aggregations

HttpConnectCallback (com.koushikdutta.async.http.callback.HttpConnectCallback)7 TimeoutException (java.util.concurrent.TimeoutException)6 AsyncSSLException (com.koushikdutta.async.AsyncSSLException)4 FileNotFoundException (java.io.FileNotFoundException)4 IOException (java.io.IOException)4 ByteBufferList (com.koushikdutta.async.ByteBufferList)3 DataEmitter (com.koushikdutta.async.DataEmitter)3 CompletedCallback (com.koushikdutta.async.callback.CompletedCallback)3 DataCallback (com.koushikdutta.async.callback.DataCallback)3 SimpleFuture (com.koushikdutta.async.future.SimpleFuture)3 AsyncHttpResponse (com.koushikdutta.async.http.AsyncHttpResponse)3 Uri (android.net.Uri)2 Cancellable (com.koushikdutta.async.future.Cancellable)2 CancellationException (java.util.concurrent.CancellationException)2 ExecutionException (java.util.concurrent.ExecutionException)2 Semaphore (java.util.concurrent.Semaphore)2 AsyncSocket (com.koushikdutta.async.AsyncSocket)1 ConnectCallback (com.koushikdutta.async.callback.ConnectCallback)1 Future (com.koushikdutta.async.future.Future)1 FutureCallback (com.koushikdutta.async.future.FutureCallback)1