Search in sources :

Example 6 with DataEmitter

use of com.koushikdutta.async.DataEmitter 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 7 with DataEmitter

use of com.koushikdutta.async.DataEmitter in project AndroidAsync by koush.

the class Dns method lookup.

public static Future<DnsResponse> lookup(AsyncServer server, String host, final boolean multicast, final FutureCallback<DnsResponse> callback) {
    ByteBuffer packet = ByteBufferList.obtain(1024).order(ByteOrder.BIG_ENDIAN);
    short id = (short) new Random().nextInt();
    short flags = (short) setQuery(0);
    if (!multicast)
        flags = (short) setRecursion(flags);
    packet.putShort(id);
    packet.putShort(flags);
    // number questions
    packet.putShort(multicast ? (short) 1 : (short) 2);
    // number answer rr
    packet.putShort((short) 0);
    // number authority rr
    packet.putShort((short) 0);
    // number additional rr
    packet.putShort((short) 0);
    addName(packet, host);
    // query
    packet.putShort(multicast ? (short) 12 : (short) 1);
    // request internet address
    packet.putShort((short) 1);
    if (!multicast) {
        addName(packet, host);
        // AAAA query
        packet.putShort((short) 28);
        // request internet address
        packet.putShort((short) 1);
    }
    packet.flip();
    try {
        final AsyncDatagramSocket dgram;
        // todo, use the dns server...
        if (!multicast) {
            dgram = server.connectDatagram(new InetSocketAddress("8.8.8.8", 53));
        } else {
            //                System.out.println("multicast dns...");
            dgram = AsyncServer.getDefault().openDatagram(new InetSocketAddress(0), true);
            Field field = DatagramSocket.class.getDeclaredField("impl");
            field.setAccessible(true);
            Object impl = field.get(dgram.getSocket());
            Method method = impl.getClass().getDeclaredMethod("join", InetAddress.class);
            method.setAccessible(true);
            method.invoke(impl, InetAddress.getByName("224.0.0.251"));
            ((DatagramSocket) dgram.getSocket()).setBroadcast(true);
        }
        final SimpleFuture<DnsResponse> ret = new SimpleFuture<DnsResponse>() {

            @Override
            protected void cleanup() {
                super.cleanup();
                //                    System.out.println("multicast dns cleanup...");
                dgram.close();
            }
        };
        dgram.setDataCallback(new DataCallback() {

            @Override
            public void onDataAvailable(DataEmitter emitter, ByteBufferList bb) {
                try {
                    //                        System.out.println(dgram.getRemoteAddress());
                    DnsResponse response = DnsResponse.parse(bb);
                    //                        System.out.println(response);
                    response.source = dgram.getRemoteAddress();
                    if (!multicast) {
                        dgram.close();
                        ret.setComplete(response);
                    } else {
                        callback.onCompleted(null, response);
                    }
                } catch (Exception e) {
                }
                bb.recycle();
            }
        });
        if (!multicast)
            dgram.write(new ByteBufferList(packet));
        else
            dgram.send(new InetSocketAddress("224.0.0.251", 5353), packet);
        return ret;
    } catch (Exception e) {
        SimpleFuture<DnsResponse> ret = new SimpleFuture<DnsResponse>();
        ret.setComplete(e);
        if (multicast)
            callback.onCompleted(e, null);
        return ret;
    }
}
Also used : ByteBufferList(com.koushikdutta.async.ByteBufferList) InetSocketAddress(java.net.InetSocketAddress) Method(java.lang.reflect.Method) DataCallback(com.koushikdutta.async.callback.DataCallback) ByteBuffer(java.nio.ByteBuffer) AsyncDatagramSocket(com.koushikdutta.async.AsyncDatagramSocket) Field(java.lang.reflect.Field) Random(java.util.Random) AsyncDatagramSocket(com.koushikdutta.async.AsyncDatagramSocket) DatagramSocket(java.net.DatagramSocket) DataEmitter(com.koushikdutta.async.DataEmitter) SimpleFuture(com.koushikdutta.async.future.SimpleFuture)

Example 8 with DataEmitter

use of com.koushikdutta.async.DataEmitter in project AndroidAsync by koush.

the class AsyncSocketMiddleware method idleSocket.

private void idleSocket(final AsyncSocket socket) {
    // must listen for socket close, otherwise log will get spammed.
    socket.setEndCallback(new CompletedCallback() {

        @Override
        public void onCompleted(Exception ex) {
            socket.setClosedCallback(null);
            socket.close();
        }
    });
    socket.setWriteableCallback(null);
    // should not get any data after this point...
    // if so, eat it and disconnect.
    socket.setDataCallback(new DataCallback.NullDataCallback() {

        @Override
        public void onDataAvailable(DataEmitter emitter, ByteBufferList bb) {
            super.onDataAvailable(emitter, bb);
            bb.recycle();
            socket.setClosedCallback(null);
            socket.close();
        }
    });
}
Also used : CompletedCallback(com.koushikdutta.async.callback.CompletedCallback) ByteBufferList(com.koushikdutta.async.ByteBufferList) DataEmitter(com.koushikdutta.async.DataEmitter) DataCallback(com.koushikdutta.async.callback.DataCallback)

Example 9 with DataEmitter

use of com.koushikdutta.async.DataEmitter in project PushSms by koush.

the class MiddlewareService method findOrCreateGcmSocket.

// given a registration, find/create the gcm socket that manages
// the secure connection between the two devices.
private GcmSocket findOrCreateGcmSocket(Registration registration) {
    GcmSocket ret = gcmConnectionManager.findGcmSocket(registration);
    if (ret == null) {
        final GcmSocket gcmSocket = ret = gcmConnectionManager.createGcmSocket(registration, getNumber());
        // parse data from the gcm connection as we get it
        ret.setDataCallback(new DataCallback() {

            @Override
            public void onDataAvailable(DataEmitter emitter, ByteBufferList bb) {
                parseGcmMessage(gcmSocket, bb);
                // save the registration info (sequence numbers changed, etc)
                registry.register(gcmSocket.registration.endpoint, gcmSocket.registration);
            }
        });
        // on error, fail over any pending messages for this number
        ret.setEndCallback(new CompletedCallback() {

            @Override
            public void onCompleted(Exception ex) {
                for (String pending : new ArrayList<String>(messagesAwaitingAck.keySet())) {
                    String numberPart = pending.split(":")[0];
                    if (!PhoneNumberUtils.compare(MiddlewareService.this, numberPart, gcmSocket.getNumber()))
                        continue;
                    GcmText gcmText = messagesAwaitingAck.get(pending);
                    if (gcmText == null)
                        continue;
                    gcmText.manageFailure(handler, smsManager);
                }
            }
        });
    }
    return ret;
}
Also used : CompletedCallback(com.koushikdutta.async.callback.CompletedCallback) ByteBufferList(com.koushikdutta.async.ByteBufferList) GcmSocket(org.cyanogenmod.pushsms.socket.GcmSocket) DataEmitter(com.koushikdutta.async.DataEmitter) DataCallback(com.koushikdutta.async.callback.DataCallback) RemoteException(android.os.RemoteException) IOException(java.io.IOException)

Example 10 with DataEmitter

use of com.koushikdutta.async.DataEmitter in project AndroidAsync by koush.

the class MultipartTests method setUp.

@Override
protected void setUp() throws Exception {
    super.setUp();
    httpServer = new AsyncHttpServer();
    httpServer.setErrorCallback(new CompletedCallback() {

        @Override
        public void onCompleted(Exception ex) {
            fail();
        }
    });
    httpServer.listen(AsyncServer.getDefault(), 5000);
    httpServer.post("/", new HttpServerRequestCallback() {

        int gotten = 0;

        @Override
        public void onRequest(final AsyncHttpServerRequest request, final AsyncHttpServerResponse response) {
            final MultipartFormDataBody body = (MultipartFormDataBody) request.getBody();
            body.setMultipartCallback(new MultipartCallback() {

                @Override
                public void onPart(Part part) {
                    if (part.isFile()) {
                        body.setDataCallback(new DataCallback() {

                            @Override
                            public void onDataAvailable(DataEmitter emitter, ByteBufferList bb) {
                                gotten += bb.remaining();
                                bb.recycle();
                            }
                        });
                    }
                }
            });
            request.setEndCallback(new CompletedCallback() {

                @Override
                public void onCompleted(Exception ex) {
                    response.send(body.getField("baz") + gotten + body.getField("foo"));
                }
            });
        }
    });
}
Also used : CompletedCallback(com.koushikdutta.async.callback.CompletedCallback) HttpServerRequestCallback(com.koushikdutta.async.http.server.HttpServerRequestCallback) ByteBufferList(com.koushikdutta.async.ByteBufferList) AsyncHttpServerRequest(com.koushikdutta.async.http.server.AsyncHttpServerRequest) AsyncHttpServerResponse(com.koushikdutta.async.http.server.AsyncHttpServerResponse) MultipartCallback(com.koushikdutta.async.http.body.MultipartFormDataBody.MultipartCallback) DataCallback(com.koushikdutta.async.callback.DataCallback) Part(com.koushikdutta.async.http.body.Part) DataEmitter(com.koushikdutta.async.DataEmitter) AsyncHttpServer(com.koushikdutta.async.http.server.AsyncHttpServer) MultipartFormDataBody(com.koushikdutta.async.http.body.MultipartFormDataBody)

Aggregations

DataEmitter (com.koushikdutta.async.DataEmitter)17 ByteBufferList (com.koushikdutta.async.ByteBufferList)14 DataCallback (com.koushikdutta.async.callback.DataCallback)12 CompletedCallback (com.koushikdutta.async.callback.CompletedCallback)10 IOException (java.io.IOException)7 TimeoutException (java.util.concurrent.TimeoutException)4 SimpleFuture (com.koushikdutta.async.future.SimpleFuture)3 HttpConnectCallback (com.koushikdutta.async.http.callback.HttpConnectCallback)3 ByteBuffer (java.nio.ByteBuffer)3 Semaphore (java.util.concurrent.Semaphore)3 AsyncSSLException (com.koushikdutta.async.AsyncSSLException)2 AsyncSocket (com.koushikdutta.async.AsyncSocket)2 FilteredDataEmitter (com.koushikdutta.async.FilteredDataEmitter)2 LineEmitter (com.koushikdutta.async.LineEmitter)2 AsyncHttpResponse (com.koushikdutta.async.http.AsyncHttpResponse)2 Headers (com.koushikdutta.async.http.Headers)2 AsyncHttpRequestBody (com.koushikdutta.async.http.body.AsyncHttpRequestBody)2 FileNotFoundException (java.io.FileNotFoundException)2 CancellationException (java.util.concurrent.CancellationException)2 ExecutionException (java.util.concurrent.ExecutionException)2