Search in sources :

Example 1 with SimpleFuture

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

the class SocketIOConnection method reconnect.

void reconnect(final DependentCancellable child) {
    if (isConnected()) {
        return;
    }
    // if a connection is in progress, just wait.
    if (connecting != null && !connecting.isDone() && !connecting.isCancelled()) {
        if (child != null)
            child.setParent(connecting);
        return;
    }
    request.logi("Reconnecting socket.io");
    connecting = httpClient.executeString(request, null).then(new TransformFuture<SocketIOTransport, String>() {

        @Override
        protected void transform(String result) throws Exception {
            String[] parts = result.split(":");
            final String sessionId = parts[0];
            if (!"".equals(parts[1]))
                heartbeat = Integer.parseInt(parts[1]) / 2 * 1000;
            else
                heartbeat = 0;
            String transportsLine = parts[3];
            String[] transports = transportsLine.split(",");
            HashSet<String> set = new HashSet<String>(Arrays.asList(transports));
            final SimpleFuture<SocketIOTransport> transport = new SimpleFuture<SocketIOTransport>();
            if (set.contains("websocket")) {
                final String sessionUrl = Uri.parse(request.getUri().toString()).buildUpon().appendPath("websocket").appendPath(sessionId).build().toString();
                httpClient.websocket(sessionUrl, null, null).setCallback(new FutureCallback<WebSocket>() {

                    @Override
                    public void onCompleted(Exception e, WebSocket result) {
                        if (e != null) {
                            transport.setComplete(e);
                            return;
                        }
                        transport.setComplete(new WebSocketTransport(result, sessionId));
                    }
                });
            } else if (set.contains("xhr-polling")) {
                final String sessionUrl = Uri.parse(request.getUri().toString()).buildUpon().appendPath("xhr-polling").appendPath(sessionId).build().toString();
                XHRPollingTransport xhrPolling = new XHRPollingTransport(httpClient, sessionUrl, sessionId);
                transport.setComplete(xhrPolling);
            } else {
                throw new SocketIOException("transport not supported");
            }
            setComplete(transport);
        }
    }).setCallback(new FutureCallback<SocketIOTransport>() {

        @Override
        public void onCompleted(Exception e, SocketIOTransport result) {
            if (e != null) {
                reportDisconnect(e);
                return;
            }
            reconnectDelay = request.config.reconnectDelay;
            SocketIOConnection.this.transport = result;
            attach();
        }
    });
    if (child != null)
        child.setParent(connecting);
}
Also used : WebSocket(com.koushikdutta.async.http.WebSocket) SocketIOTransport(com.koushikdutta.async.http.socketio.transport.SocketIOTransport) WebSocketTransport(com.koushikdutta.async.http.socketio.transport.WebSocketTransport) XHRPollingTransport(com.koushikdutta.async.http.socketio.transport.XHRPollingTransport) FutureCallback(com.koushikdutta.async.future.FutureCallback) HashSet(java.util.HashSet) SimpleFuture(com.koushikdutta.async.future.SimpleFuture)

Example 2 with SimpleFuture

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

the class AsyncServer method connectSocket.

public Cancellable connectSocket(final InetSocketAddress remote, final ConnectCallback callback) {
    if (!remote.isUnresolved())
        return connectResolvedInetSocketAddress(remote, callback);
    final SimpleFuture<AsyncNetworkSocket> ret = new SimpleFuture<AsyncNetworkSocket>();
    Future<InetAddress> lookup = getByName(remote.getHostName());
    ret.setParent(lookup);
    lookup.setCallback(new FutureCallback<InetAddress>() {

        @Override
        public void onCompleted(Exception e, InetAddress result) {
            if (e != null) {
                callback.onConnectCompleted(e, null);
                ret.setComplete(e);
                return;
            }
            ret.setComplete(connectResolvedInetSocketAddress(new InetSocketAddress(result, remote.getPort()), callback));
        }
    });
    return ret;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) InetAddress(java.net.InetAddress) CancelledKeyException(java.nio.channels.CancelledKeyException) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException) SimpleFuture(com.koushikdutta.async.future.SimpleFuture)

Example 3 with SimpleFuture

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

the class AsyncServer method createDatagram.

private Cancellable createDatagram(ValueFunction<InetAddress> inetAddressValueFunction, final int port, final boolean reuseAddress, FutureCallback<AsyncDatagramSocket> callback) {
    SimpleFuture<AsyncDatagramSocket> ret = new SimpleFuture<>();
    ret.setCallback(callback);
    post(() -> {
        DatagramChannel socket = null;
        try {
            socket = DatagramChannel.open();
            final AsyncDatagramSocket handler = new AsyncDatagramSocket();
            handler.attach(socket);
            InetSocketAddress address;
            if (inetAddressValueFunction == null)
                address = new InetSocketAddress(port);
            else
                address = new InetSocketAddress(inetAddressValueFunction.getValue(), port);
            if (reuseAddress)
                socket.socket().setReuseAddress(reuseAddress);
            socket.socket().bind(address);
            handleSocket(handler);
            if (!ret.setComplete(handler))
                socket.close();
        } catch (Exception e) {
            StreamUtility.closeQuietly(socket);
            ret.setComplete(e);
        }
    });
    return ret;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) DatagramChannel(java.nio.channels.DatagramChannel) CancelledKeyException(java.nio.channels.CancelledKeyException) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException) ClosedSelectorException(java.nio.channels.ClosedSelectorException) SimpleFuture(com.koushikdutta.async.future.SimpleFuture)

Example 4 with SimpleFuture

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

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

the class AsyncHttpServerRouter method ensureManifest.

static synchronized Manifest ensureManifest(Context context) {
    Future<Manifest> future = AppManifests.get(context.getPackageName());
    if (future != null)
        return future.tryGet();
    ZipFile zip = null;
    SimpleFuture<Manifest> result = new SimpleFuture<>();
    try {
        zip = new ZipFile(context.getPackageResourcePath());
        ZipEntry entry = zip.getEntry("META-INF/MANIFEST.MF");
        Manifest manifest = new Manifest(zip.getInputStream(entry));
        result.setComplete(manifest);
        return manifest;
    } catch (Exception e) {
        result.setComplete(e);
        return null;
    } finally {
        StreamUtility.closeQuietly(zip);
        AppManifests.put(context.getPackageName(), result);
    }
}
Also used : ZipFile(java.util.zip.ZipFile) ZipEntry(java.util.zip.ZipEntry) Manifest(java.util.jar.Manifest) IOException(java.io.IOException) SimpleFuture(com.koushikdutta.async.future.SimpleFuture)

Aggregations

SimpleFuture (com.koushikdutta.async.future.SimpleFuture)19 IOException (java.io.IOException)6 Bitmap (android.graphics.Bitmap)5 Point (android.graphics.Point)5 BitmapInfo (com.koushikdutta.ion.bitmap.BitmapInfo)5 ByteBufferList (com.koushikdutta.async.ByteBufferList)4 DataEmitter (com.koushikdutta.async.DataEmitter)4 CompletedCallback (com.koushikdutta.async.callback.CompletedCallback)4 DataCallback (com.koushikdutta.async.callback.DataCallback)4 File (java.io.File)4 InetSocketAddress (java.net.InetSocketAddress)4 TimeoutException (java.util.concurrent.TimeoutException)4 AsyncSSLException (com.koushikdutta.async.AsyncSSLException)3 Cancellable (com.koushikdutta.async.future.Cancellable)3 HttpConnectCallback (com.koushikdutta.async.http.callback.HttpConnectCallback)3 FileNotFoundException (java.io.FileNotFoundException)3 Future (com.koushikdutta.async.future.Future)2 FutureCallback (com.koushikdutta.async.future.FutureCallback)2 InputStream (java.io.InputStream)2 CancelledKeyException (java.nio.channels.CancelledKeyException)2