All Downloads are FREE. Search and download functionalities are using the official Maven repository.

co.easimart.EasimartAWSRequest Maven / Gradle / Ivy

package co.easimart;

import co.easimart.http.EasimartHttpRequest;
import co.easimart.http.EasimartHttpResponse;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.concurrent.Callable;

import bolts.Task;

/**
 * Request returns a byte array of the response and provides a callback the progress of the data
 * read from the network.
 */
/** package */ class EasimartAWSRequest extends EasimartRequest {

  // The temp file is used to save the EasimartFile content when we fetch it from server
  private final File tempFile;

  public EasimartAWSRequest(EasimartHttpRequest.Method method, String url, File tempFile) {
    super(method, url);
    this.tempFile = tempFile;
  }

  @Override
  protected Task onResponseAsync(final EasimartHttpResponse response,
      final ProgressCallback downloadProgressCallback) {
    int statusCode = response.getStatusCode();
    if (statusCode >= 200 && statusCode < 300 || statusCode == 304) {
      // OK
    } else {
      String action = method == EasimartHttpRequest.Method.GET ? "Download from" : "Upload to";
      return Task.forError(new EasimartException(EasimartException.CONNECTION_FAILED, String.format(
        "%s S3 failed. %s", action, response.getReasonPhrase())));
    }

    if (method != EasimartHttpRequest.Method.GET) {
      return null;
    }

    return Task.call(new Callable() {
      @Override
      public Void call() throws Exception {
        long totalSize = response.getTotalSize();
        long downloadedSize = 0;
        InputStream responseStream = null;
        try {
          responseStream = response.getContent();
          FileOutputStream tempFileStream = EasimartFileUtils.openOutputStream(tempFile);

          int nRead;
          byte[] data = new byte[32 << 10]; // 32KB

          while ((nRead = responseStream.read(data, 0, data.length)) != -1) {
            tempFileStream.write(data, 0, nRead);
            downloadedSize += nRead;
            if (downloadProgressCallback != null && totalSize != -1) {
              int progressToReport =
                  Math.round((float) downloadedSize / (float) totalSize * 100.0f);
              downloadProgressCallback.done(progressToReport);
            }
          }
          return null;
        } finally {
          EasimartIOUtils.closeQuietly(responseStream);
        }
      }
    }, EasimartExecutors.io());
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy