Search in sources :

Example 1 with Cancellable

use of com.koushikdutta.async.future.Cancellable in project AndroidAsync by koush.

the class SpdyMiddleware method getSocket.

@Override
public Cancellable getSocket(final GetSocketData data) {
    final Uri uri = data.request.getUri();
    final int port = getSchemePort(data.request.getUri());
    if (port == -1) {
        return null;
    }
    if (!spdyEnabled)
        return super.getSocket(data);
    // but app engine sends a GO_AWAY if it sees a content-length...
    if (!canSpdyRequest(data))
        return super.getSocket(data);
    // can we use an existing connection to satisfy this, or do we need a new one?
    String key = uri.getHost() + port;
    SpdyConnectionWaiter conn = connections.get(key);
    if (conn != null) {
        if (conn.tryGetException() instanceof NoSpdyException)
            return super.getSocket(data);
        // dead connection check
        if (conn.tryGet() != null && !conn.tryGet().socket.isOpen()) {
            // old spdy connection is derped, kill it with fire.
            connections.remove(key);
            conn = null;
        }
    }
    if (conn == null) {
        // no connection has ever been attempted (or previous one had a network death), so attempt one
        data.state.put("spdykey", key);
        // if we got something back synchronously, it's a keep alive socket
        Cancellable ret = super.getSocket(data);
        if (ret.isDone() || ret.isCancelled())
            return ret;
        conn = new SpdyConnectionWaiter();
        connections.put(key, conn);
        return conn.originalCancellable;
    }
    data.request.logv("waiting for potential spdy connection for host: " + data.request.getUri().getHost());
    final SimpleCancellable ret = new SimpleCancellable();
    conn.setCallback(new FutureCallback<AsyncSpdyConnection>() {

        @Override
        public void onCompleted(Exception e, AsyncSpdyConnection conn) {
            if (e instanceof NoSpdyException) {
                data.request.logv("spdy not available");
                ret.setParent(SpdyMiddleware.super.getSocket(data));
                return;
            }
            if (e != null) {
                if (ret.setComplete())
                    data.connectCallback.onConnectCompleted(e, null);
                return;
            }
            data.request.logv("using existing spdy connection for host: " + data.request.getUri().getHost());
            if (ret.setComplete())
                newSocket(data, conn, data.connectCallback);
        }
    });
    return ret;
}
Also used : SimpleCancellable(com.koushikdutta.async.future.SimpleCancellable) Cancellable(com.koushikdutta.async.future.Cancellable) SimpleCancellable(com.koushikdutta.async.future.SimpleCancellable) Uri(android.net.Uri) IOException(java.io.IOException)

Example 2 with Cancellable

use of com.koushikdutta.async.future.Cancellable 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 3 with Cancellable

use of com.koushikdutta.async.future.Cancellable 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 Cancellable

use of com.koushikdutta.async.future.Cancellable in project AndroidAsync by koush.

the class AsyncSocketMiddleware method nextConnection.

private void nextConnection(AsyncHttpRequest request) {
    Uri uri = request.getUri();
    final int port = getSchemePort(uri);
    String key = computeLookup(uri, port, request.getProxyHost(), request.getProxyPort());
    synchronized (AsyncSocketMiddleware.this) {
        ConnectionInfo info = connectionInfo.get(key);
        if (info == null)
            return;
        --info.openCount;
        while (info.openCount < maxConnectionCount && info.queue.size() > 0) {
            GetSocketData gsd = info.queue.remove();
            SimpleCancellable socketCancellable = (SimpleCancellable) gsd.socketCancellable;
            if (socketCancellable.isCancelled())
                continue;
            Cancellable connect = getSocket(gsd);
            socketCancellable.setParent(connect);
        }
        maybeCleanupConnectionInfo(key);
    }
}
Also used : Cancellable(com.koushikdutta.async.future.Cancellable) SimpleCancellable(com.koushikdutta.async.future.SimpleCancellable) SimpleCancellable(com.koushikdutta.async.future.SimpleCancellable) Uri(android.net.Uri)

Aggregations

Cancellable (com.koushikdutta.async.future.Cancellable)4 Uri (android.net.Uri)3 IOException (java.io.IOException)3 AsyncSSLException (com.koushikdutta.async.AsyncSSLException)2 SimpleCancellable (com.koushikdutta.async.future.SimpleCancellable)2 HttpConnectCallback (com.koushikdutta.async.http.callback.HttpConnectCallback)2 FileNotFoundException (java.io.FileNotFoundException)2 TimeoutException (java.util.concurrent.TimeoutException)2 AsyncSocket (com.koushikdutta.async.AsyncSocket)1 ConnectCallback (com.koushikdutta.async.callback.ConnectCallback)1 SimpleFuture (com.koushikdutta.async.future.SimpleFuture)1