Search in sources :

Example 6 with CompletedCallback

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

the class AsyncHttpServerResponseImpl method proxy.

@Override
public void proxy(final AsyncHttpResponse remoteResponse) {
    code(remoteResponse.code());
    remoteResponse.headers().removeAll("Transfer-Encoding");
    remoteResponse.headers().removeAll("Content-Encoding");
    remoteResponse.headers().removeAll("Connection");
    getHeaders().addAll(remoteResponse.headers());
    // TODO: remove?
    remoteResponse.headers().set("Connection", "close");
    Util.pump(remoteResponse, this, new CompletedCallback() {

        @Override
        public void onCompleted(Exception ex) {
            remoteResponse.setEndCallback(new NullCompletedCallback());
            remoteResponse.setDataCallback(new DataCallback.NullDataCallback());
            end();
        }
    });
}
Also used : CompletedCallback(com.koushikdutta.async.callback.CompletedCallback) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 7 with CompletedCallback

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

the class AsyncHttpServerResponseImpl method initFirstWrite.

void initFirstWrite() {
    if (headWritten)
        return;
    headWritten = true;
    final boolean isChunked;
    String currentEncoding = mRawHeaders.get("Transfer-Encoding");
    if ("".equals(currentEncoding))
        mRawHeaders.removeAll("Transfer-Encoding");
    boolean canUseChunked = ("Chunked".equalsIgnoreCase(currentEncoding) || currentEncoding == null) && !"close".equalsIgnoreCase(mRawHeaders.get("Connection"));
    if (mContentLength < 0) {
        String contentLength = mRawHeaders.get("Content-Length");
        if (!TextUtils.isEmpty(contentLength))
            mContentLength = Long.valueOf(contentLength);
    }
    if (mContentLength < 0 && canUseChunked) {
        mRawHeaders.set("Transfer-Encoding", "Chunked");
        isChunked = true;
    } else {
        isChunked = false;
    }
    String statusLine = String.format(Locale.ENGLISH, "HTTP/1.1 %s %s", code, AsyncHttpServer.getResponseCodeDescription(code));
    String rh = mRawHeaders.toPrefixString(statusLine);
    Util.writeAll(mSocket, rh.getBytes(), new CompletedCallback() {

        @Override
        public void onCompleted(Exception ex) {
            if (ex != null) {
                report(ex);
                return;
            }
            if (isChunked) {
                ChunkedOutputFilter chunked = new ChunkedOutputFilter(mSocket);
                chunked.setMaxBuffer(0);
                mSink = chunked;
            } else {
                mSink = mSocket;
            }
            mSink.setClosedCallback(closedCallback);
            closedCallback = null;
            mSink.setWriteableCallback(writable);
            writable = null;
            if (ended) {
                // the response ended while headers were written
                end();
                return;
            }
            getServer().post(new Runnable() {

                @Override
                public void run() {
                    WritableCallback wb = getWriteableCallback();
                    if (wb != null)
                        wb.onWriteable();
                }
            });
        }
    });
}
Also used : CompletedCallback(com.koushikdutta.async.callback.CompletedCallback) WritableCallback(com.koushikdutta.async.callback.WritableCallback) ChunkedOutputFilter(com.koushikdutta.async.http.filter.ChunkedOutputFilter) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 8 with CompletedCallback

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

the class AsyncHttpServerResponseImpl method sendStream.

@Override
public void sendStream(final InputStream inputStream, long totalLength) {
    long start = 0;
    long end = totalLength - 1;
    String range = mRequest.getHeaders().get("Range");
    if (range != null) {
        String[] parts = range.split("=");
        if (parts.length != 2 || !"bytes".equals(parts[0])) {
            // Requested range not satisfiable
            code(416);
            end();
            return;
        }
        parts = parts[1].split("-");
        try {
            if (parts.length > 2)
                throw new MalformedRangeException();
            if (!TextUtils.isEmpty(parts[0]))
                start = Long.parseLong(parts[0]);
            if (parts.length == 2 && !TextUtils.isEmpty(parts[1]))
                end = Long.parseLong(parts[1]);
            else
                end = totalLength - 1;
            code(206);
            getHeaders().set("Content-Range", String.format(Locale.ENGLISH, "bytes %d-%d/%d", start, end, totalLength));
        } catch (Exception e) {
            code(416);
            end();
            return;
        }
    }
    try {
        if (start != inputStream.skip(start))
            throw new StreamSkipException("skip failed to skip requested amount");
        mContentLength = end - start + 1;
        mRawHeaders.set("Content-Length", String.valueOf(mContentLength));
        mRawHeaders.set("Accept-Ranges", "bytes");
        if (mRequest.getMethod().equals(AsyncHttpHead.METHOD)) {
            writeHead();
            onEnd();
            return;
        }
        Util.pump(inputStream, mContentLength, this, new CompletedCallback() {

            @Override
            public void onCompleted(Exception ex) {
                StreamUtility.closeQuietly(inputStream);
                onEnd();
            }
        });
    } catch (Exception e) {
        code(500);
        end();
    }
}
Also used : CompletedCallback(com.koushikdutta.async.callback.CompletedCallback) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 9 with CompletedCallback

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

the class HttpServerTests 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.get("/hello", new HttpServerRequestCallback() {

        @Override
        public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
            assertNotNull(request.getHeaders().get("Host"));
            response.send("hello");
        }
    });
    httpServer.post("/echo", new HttpServerRequestCallback() {

        @Override
        public void onRequest(AsyncHttpServerRequest request, final AsyncHttpServerResponse response) {
            try {
                assertNotNull(request.getHeaders().get("Host"));
                JSONObject json = new JSONObject();
                if (request.getBody() instanceof UrlEncodedFormBody) {
                    UrlEncodedFormBody body = (UrlEncodedFormBody) request.getBody();
                    for (NameValuePair pair : body.get()) {
                        json.put(pair.getName(), pair.getValue());
                    }
                } else if (request.getBody() instanceof JSONObjectBody) {
                    json = ((JSONObjectBody) request.getBody()).get();
                } else if (request.getBody() instanceof StringBody) {
                    json.put("foo", ((StringBody) request.getBody()).get());
                } else if (request.getBody() instanceof MultipartFormDataBody) {
                    MultipartFormDataBody body = (MultipartFormDataBody) request.getBody();
                    for (NameValuePair pair : body.get()) {
                        json.put(pair.getName(), pair.getValue());
                    }
                }
                response.send(json);
            } catch (Exception e) {
            }
        }
    });
}
Also used : NameValuePair(com.koushikdutta.async.http.NameValuePair) CompletedCallback(com.koushikdutta.async.callback.CompletedCallback) HttpServerRequestCallback(com.koushikdutta.async.http.server.HttpServerRequestCallback) AsyncHttpServerRequest(com.koushikdutta.async.http.server.AsyncHttpServerRequest) AsyncHttpServerResponse(com.koushikdutta.async.http.server.AsyncHttpServerResponse) JSONObjectBody(com.koushikdutta.async.http.body.JSONObjectBody) JSONObject(org.json.JSONObject) StringBody(com.koushikdutta.async.http.body.StringBody) AsyncHttpServer(com.koushikdutta.async.http.server.AsyncHttpServer) UrlEncodedFormBody(com.koushikdutta.async.http.body.UrlEncodedFormBody) MultipartFormDataBody(com.koushikdutta.async.http.body.MultipartFormDataBody)

Example 10 with CompletedCallback

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

the class FutureTests method testContinuationArray.

public void testContinuationArray() throws Exception {
    final ArrayList<Integer> results = new ArrayList<Integer>();
    final Semaphore semaphore = new Semaphore(0);
    final Continuation c = new Continuation(new CompletedCallback() {

        @Override
        public void onCompleted(Exception ex) {
            semaphore.release();
        }
    });
    for (int i = 0; i < 10; i++) {
        final int j = i;
        c.add(new ContinuationCallback() {

            @Override
            public void onContinue(Continuation continuation, CompletedCallback next) throws Exception {
                results.add(j);
                next.onCompleted(null);
            }
        });
    }
    new Thread() {

        public void run() {
            c.start();
        }

        ;
    }.start();
    assertTrue(semaphore.tryAcquire(3000, TimeUnit.MILLISECONDS));
    assertEquals(10, results.size());
    for (int i = 0; i < 10; i++) {
        assertEquals((int) results.get(i), i);
    }
}
Also used : Continuation(com.koushikdutta.async.future.Continuation) CompletedCallback(com.koushikdutta.async.callback.CompletedCallback) ArrayList(java.util.ArrayList) ContinuationCallback(com.koushikdutta.async.callback.ContinuationCallback) Semaphore(java.util.concurrent.Semaphore) CancellationException(java.util.concurrent.CancellationException) TimeoutException(java.util.concurrent.TimeoutException) ExecutionException(java.util.concurrent.ExecutionException)

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