Search in sources :

Example 11 with DataEmitter

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

Example 12 with DataEmitter

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

the class HttpClientTests method testClockworkMod.

public void testClockworkMod() throws Exception {
    final Semaphore semaphore = new Semaphore(0);
    final Md5 md5 = Md5.createInstance();
    client.execute("http://www.clockworkmod.com", new HttpConnectCallback() {

        @Override
        public void onConnectCompleted(Exception ex, AsyncHttpResponse response) {
            // make sure gzip decoding works, as that is generally what github sends.
            Assert.assertEquals("gzip", response.headers().get("Content-Encoding"));
            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));
}
Also used : 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)

Example 13 with DataEmitter

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

Example 14 with DataEmitter

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

the class UrlEncodedFormBody method parse.

@Override
public void parse(DataEmitter emitter, final CompletedCallback completed) {
    final ByteBufferList data = new ByteBufferList();
    emitter.setDataCallback(new DataCallback() {

        @Override
        public void onDataAvailable(DataEmitter emitter, ByteBufferList bb) {
            bb.get(data);
        }
    });
    emitter.setEndCallback(new CompletedCallback() {

        @Override
        public void onCompleted(Exception ex) {
            if (ex != null) {
                completed.onCompleted(ex);
                return;
            }
            try {
                mParameters = Multimap.parseUrlEncoded(data.readString());
                completed.onCompleted(null);
            } catch (Exception e) {
                completed.onCompleted(e);
            }
        }
    });
}
Also used : CompletedCallback(com.koushikdutta.async.callback.CompletedCallback) ByteBufferList(com.koushikdutta.async.ByteBufferList) DataEmitter(com.koushikdutta.async.DataEmitter) DataCallback(com.koushikdutta.async.callback.DataCallback) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 15 with DataEmitter

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

the class SpdyMiddleware method exchangeHeaders.

@Override
public boolean exchangeHeaders(final OnExchangeHeaderData data) {
    if (!(data.socket instanceof AsyncSpdyConnection.SpdySocket))
        return super.exchangeHeaders(data);
    AsyncHttpRequestBody requestBody = data.request.getBody();
    if (requestBody != null) {
        data.response.sink(data.socket);
    }
    // headers were already sent as part of the socket being opened.
    data.sendHeadersCallback.onCompleted(null);
    final AsyncSpdyConnection.SpdySocket spdySocket = (AsyncSpdyConnection.SpdySocket) data.socket;
    spdySocket.headers().then(new TransformFuture<Headers, List<Header>>() {

        @Override
        protected void transform(List<Header> result) throws Exception {
            Headers headers = new Headers();
            for (Header header : result) {
                String key = header.name.utf8();
                String value = header.value.utf8();
                headers.add(key, value);
            }
            String status = headers.remove(Header.RESPONSE_STATUS.utf8());
            String[] statusParts = status.split(" ", 2);
            data.response.code(Integer.parseInt(statusParts[0]));
            if (statusParts.length == 2)
                data.response.message(statusParts[1]);
            data.response.protocol(headers.remove(Header.VERSION.utf8()));
            data.response.headers(headers);
            setComplete(headers);
        }
    }).setCallback(new FutureCallback<Headers>() {

        @Override
        public void onCompleted(Exception e, Headers result) {
            data.receiveHeadersCallback.onCompleted(e);
            DataEmitter emitter = HttpUtil.getBodyDecoder(spdySocket, spdySocket.getConnection().protocol, result, false);
            data.response.emitter(emitter);
        }
    });
    return true;
}
Also used : Headers(com.koushikdutta.async.http.Headers) IOException(java.io.IOException) DataEmitter(com.koushikdutta.async.DataEmitter) ArrayList(java.util.ArrayList) ByteBufferList(com.koushikdutta.async.ByteBufferList) List(java.util.List) AsyncHttpRequestBody(com.koushikdutta.async.http.body.AsyncHttpRequestBody) TransformFuture(com.koushikdutta.async.future.TransformFuture)

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