Search in sources :

Example 36 with CompletedCallback

use of com.koushikdutta.async.callback.CompletedCallback in project ion by koush.

the class Issues method testIssue312.

public void testIssue312() throws Exception {
    String b64 = "SFRUUC8xLjAgMzAyIEZvdW5kDQpTZXQtQ29va2ll\n" + "OlNFU1NJT049NUJBRDlERTEwQjY0NjgwNDsKTG9j\n" + "YXRpb246IGhvbWUuY2dpCkNvbnRlbnQtdHlwZTog\n" + "dGV4dC9odG1sCgo8aHRtbD48aGVhZD48bWV0YSBo\n" + "dHRwLWVxdWl2PSdyZWZyZXNoJyBjb250ZW50PScw\n" + "OyB1cmw9aG9tZS5jZ2knPjwvbWV0YT48L2hlYWQ+\n" + "PGJvZHk+PC9ib2R5PjwvaHRtbD4K";
    /*
        HTTP/1.0 302 Found
        Set-Cookie:SESSION=5BAD9DE10B646804;
        Location: home.cgi
        Content-type: text/html

        <html><head><meta http-equiv='refresh' content='0; url=home.cgi'></meta></head><body></body></html>
         */
    // the above is using newlines, and not CRLF.
    final byte[] responseData = Base64.decode(b64, 0);
    server = Ion.getDefault(getContext()).getServer().listen(null, 0, new ListenCallback() {

        @Override
        public void onAccepted(final AsyncSocket socket) {
            Util.writeAll(socket, responseData, new CompletedCallback() {

                @Override
                public void onCompleted(Exception ex) {
                    socket.end();
                    server.stop();
                }
            });
        }

        @Override
        public void onListening(AsyncServerSocket socket) {
        }

        @Override
        public void onCompleted(Exception ex) {
        }
    });
    Ion.with(getContext()).load("http://localhost:" + server.getLocalPort()).followRedirect(false).asString().get();
}
Also used : AsyncServerSocket(com.koushikdutta.async.AsyncServerSocket) AsyncSocket(com.koushikdutta.async.AsyncSocket) CompletedCallback(com.koushikdutta.async.callback.CompletedCallback) ListenCallback(com.koushikdutta.async.callback.ListenCallback)

Example 37 with CompletedCallback

use of com.koushikdutta.async.callback.CompletedCallback in project ion by koush.

the class StreamTests method setUp.

@Override
protected void setUp() throws Exception {
    super.setUp();
    AsyncHttpServer server = new AsyncHttpServer();
    port = server.listen(0).getLocalPort();
    server.get("/", new HttpServerRequestCallback() {

        @Override
        public void onRequest(AsyncHttpServerRequest request, final AsyncHttpServerResponse response) {
            response.code(200);
            ByteBuffer b = ByteBufferList.obtain(random.length);
            b.put(random);
            b.flip();
            ByteBufferList list = new ByteBufferList(b);
            Util.writeAll(response, list, new CompletedCallback() {

                @Override
                public void onCompleted(Exception ex) {
                    response.end();
                }
            });
        }
    });
}
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) AsyncHttpServer(com.koushikdutta.async.http.server.AsyncHttpServer) AsyncHttpServerResponse(com.koushikdutta.async.http.server.AsyncHttpServerResponse) ByteBuffer(java.nio.ByteBuffer)

Example 38 with CompletedCallback

use of com.koushikdutta.async.callback.CompletedCallback in project ion by koush.

the class IonRequestBuilder method execute.

<T> EmitterTransform<T> execute(final DataSink sink, final boolean close, final T result, final Runnable cancel) {
    EmitterTransform<T> ret = new EmitterTransform<T>(cancel) {

        @Override
        protected void cleanup() {
            super.cleanup();
            if (close)
                sink.end();
        }

        EmitterTransform<T> self = this;

        @Override
        protected void transform(LoaderEmitter emitter) throws Exception {
            super.transform(emitter);
            Util.pump(this.emitter, sink, new CompletedCallback() {

                @Override
                public void onCompleted(Exception ex) {
                    postExecute(self, ex, result);
                }
            });
        }
    };
    getLoaderEmitter(ret);
    return ret;
}
Also used : CompletedCallback(com.koushikdutta.async.callback.CompletedCallback) LoaderEmitter(com.koushikdutta.ion.Loader.LoaderEmitter)

Example 39 with CompletedCallback

use of com.koushikdutta.async.callback.CompletedCallback in project ion by koush.

the class FileCacheStore method put.

private <T> Future<T> put(final T value, final AsyncParser<T> parser) {
    final SimpleFuture<T> ret = new SimpleFuture<T>();
    Ion.getIoExecutorService().execute(new Runnable() {

        @Override
        public void run() {
            final String key = computeKey();
            final File file = cache.getTempFile();
            final FileDataSink sink = new FileDataSink(ion.getServer(), file);
            parser.write(sink, value, new CompletedCallback() {

                @Override
                public void onCompleted(Exception ex) {
                    sink.end();
                    if (ex != null) {
                        file.delete();
                        ret.setComplete(ex);
                        return;
                    }
                    cache.commitTempFiles(key, file);
                    ret.setComplete(value);
                }
            });
        }
    });
    return ret;
}
Also used : FileDataSink(com.koushikdutta.async.stream.FileDataSink) CompletedCallback(com.koushikdutta.async.callback.CompletedCallback) File(java.io.File) SimpleFuture(com.koushikdutta.async.future.SimpleFuture)

Example 40 with CompletedCallback

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

the class HttpTransportMiddleware method exchangeHeaders.

@Override
public boolean exchangeHeaders(final OnExchangeHeaderData data) {
    Protocol p = Protocol.get(data.protocol);
    if (p != null && p != Protocol.HTTP_1_0 && p != Protocol.HTTP_1_1)
        return super.exchangeHeaders(data);
    AsyncHttpRequest request = data.request;
    AsyncHttpRequestBody requestBody = data.request.getBody();
    if (requestBody != null) {
        if (requestBody.length() >= 0) {
            request.getHeaders().set("Content-Length", String.valueOf(requestBody.length()));
            data.response.sink(data.socket);
        } else if ("close".equals(request.getHeaders().get("Connection"))) {
            data.response.sink(data.socket);
        } else {
            request.getHeaders().set("Transfer-Encoding", "Chunked");
            data.response.sink(new ChunkedOutputFilter(data.socket));
        }
    }
    String rl = request.getRequestLine().toString();
    String rs = request.getHeaders().toPrefixString(rl);
    byte[] rsBytes = rs.getBytes();
    // try to get the request body in the same packet as the request headers... if it will fit
    // in the max MTU (1540 or whatever).
    final boolean waitForBody = requestBody != null && requestBody.length() >= 0 && requestBody.length() + rsBytes.length < 1024;
    final BufferedDataSink bsink;
    final DataSink headerSink;
    if (waitForBody) {
        // force buffering of headers
        bsink = new BufferedDataSink(data.response.sink());
        bsink.forceBuffering(true);
        data.response.sink(bsink);
        headerSink = bsink;
    } else {
        bsink = null;
        headerSink = data.socket;
    }
    request.logv("\n" + rs);
    final CompletedCallback sentCallback = data.sendHeadersCallback;
    Util.writeAll(headerSink, rsBytes, new CompletedCallback() {

        @Override
        public void onCompleted(Exception ex) {
            Util.end(sentCallback, ex);
            // flush headers and any request body that was written by the callback
            if (bsink != null) {
                bsink.forceBuffering(false);
                bsink.setMaxBuffer(0);
            }
        }
    });
    LineEmitter.StringCallback headerCallback = new LineEmitter.StringCallback() {

        Headers mRawHeaders = new Headers();

        String statusLine;

        @Override
        public void onStringAvailable(String s) {
            try {
                s = s.trim();
                if (statusLine == null) {
                    statusLine = s;
                } else if (!TextUtils.isEmpty(s)) {
                    mRawHeaders.addLine(s);
                } else {
                    String[] parts = statusLine.split(" ", 3);
                    if (parts.length < 2)
                        throw new Exception(new IOException("Not HTTP"));
                    data.response.headers(mRawHeaders);
                    String protocol = parts[0];
                    data.response.protocol(protocol);
                    data.response.code(Integer.parseInt(parts[1]));
                    data.response.message(parts.length == 3 ? parts[2] : "");
                    data.receiveHeadersCallback.onCompleted(null);
                    // socket may get detached after headers (websocket)
                    AsyncSocket socket = data.response.socket();
                    if (socket == null)
                        return;
                    DataEmitter emitter;
                    // return content length, etc, which will confuse the body decoder
                    if (AsyncHttpHead.METHOD.equalsIgnoreCase(data.request.getMethod())) {
                        emitter = HttpUtil.EndEmitter.create(socket.getServer(), null);
                    } else {
                        emitter = HttpUtil.getBodyDecoder(socket, Protocol.get(protocol), mRawHeaders, false);
                    }
                    data.response.emitter(emitter);
                }
            } catch (Exception ex) {
                data.receiveHeadersCallback.onCompleted(ex);
            }
        }
    };
    LineEmitter liner = new LineEmitter();
    data.socket.setDataCallback(liner);
    liner.setLineCallback(headerCallback);
    return true;
}
Also used : BufferedDataSink(com.koushikdutta.async.BufferedDataSink) DataSink(com.koushikdutta.async.DataSink) CompletedCallback(com.koushikdutta.async.callback.CompletedCallback) BufferedDataSink(com.koushikdutta.async.BufferedDataSink) IOException(java.io.IOException) ChunkedOutputFilter(com.koushikdutta.async.http.filter.ChunkedOutputFilter) IOException(java.io.IOException) AsyncSocket(com.koushikdutta.async.AsyncSocket) LineEmitter(com.koushikdutta.async.LineEmitter) DataEmitter(com.koushikdutta.async.DataEmitter) AsyncHttpRequestBody(com.koushikdutta.async.http.body.AsyncHttpRequestBody)

Aggregations

CompletedCallback (com.koushikdutta.async.callback.CompletedCallback)46 IOException (java.io.IOException)12 TimeoutException (java.util.concurrent.TimeoutException)11 ByteBufferList (com.koushikdutta.async.ByteBufferList)10 DataEmitter (com.koushikdutta.async.DataEmitter)10 DataCallback (com.koushikdutta.async.callback.DataCallback)10 Semaphore (java.util.concurrent.Semaphore)9 ContinuationCallback (com.koushikdutta.async.callback.ContinuationCallback)8 Continuation (com.koushikdutta.async.future.Continuation)8 CancellationException (java.util.concurrent.CancellationException)8 ExecutionException (java.util.concurrent.ExecutionException)8 AsyncHttpServer (com.koushikdutta.async.http.server.AsyncHttpServer)7 AsyncHttpServerRequest (com.koushikdutta.async.http.server.AsyncHttpServerRequest)7 FileNotFoundException (java.io.FileNotFoundException)7 AsyncHttpServerResponse (com.koushikdutta.async.http.server.AsyncHttpServerResponse)6 HttpServerRequestCallback (com.koushikdutta.async.http.server.HttpServerRequestCallback)6 AsyncSocket (com.koushikdutta.async.AsyncSocket)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)5 Uri (android.net.Uri)4 WritableCallback (com.koushikdutta.async.callback.WritableCallback)4