Search in sources :

Example 1 with MaxResourceDownloadCapacity

use of com.tvd12.ezyhttp.core.exception.MaxResourceDownloadCapacity in project ezyhttp by youngmonkeys.

the class ResourceDownloadManager method loop.

private void loop() {
    byte[] buffer = new byte[bufferSize];
    while (active) {
        Entry entry = null;
        boolean done = true;
        Exception exception = null;
        try {
            entry = queue.take();
            if (entry == POISON) {
                break;
            }
            InputStream inputStream = entry.inputStream;
            OutputStream outputStream = entry.outputStream;
            int read = inputStream.read(buffer);
            if (read > 0) {
                outputStream.write(buffer, 0, read);
                done = false;
            }
        } catch (Exception e) {
            exception = e;
            logger.info("download error", e);
        } catch (Throwable e) {
            exception = new IllegalStateException(e);
            logger.info("download fatal error", e);
        }
        if (entry == null) {
            continue;
        }
        try {
            if (done) {
                EzyFuture future = futureMap.removeFuture(entry);
                if (future == null) {
                    continue;
                }
                if (exception != null) {
                    future.setException(exception);
                } else {
                    future.setResult(Boolean.TRUE);
                }
            } else {
                if (!queue.offer(entry)) {
                    EzyFuture future = futureMap.removeFuture(entry);
                    if (future != null) {
                        future.setException(new MaxResourceDownloadCapacity(capacity));
                    }
                }
            }
        } catch (Throwable e) {
            logger.info("handle download result error", e);
        }
    }
}
Also used : InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) MaxResourceDownloadCapacity(com.tvd12.ezyhttp.core.exception.MaxResourceDownloadCapacity) EzyFuture(com.tvd12.ezyfox.concurrent.EzyFuture)

Aggregations

EzyFuture (com.tvd12.ezyfox.concurrent.EzyFuture)1 MaxResourceDownloadCapacity (com.tvd12.ezyhttp.core.exception.MaxResourceDownloadCapacity)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1