Download file from Amazon AWS private Bucket

Download file from AWS S3 private Bucket

Amazon is providing many of the APIs, all are used in different scenarios,

Here, our aim is to download file using Amazon API, for that amazon's AWS S3 from SDK is used.

Add below dependency in your app's gradle file
compile 'com.amazonaws:aws-android-sdk-s3:2.3.0'
below are the classes you need to import
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.mobileconnectors.s3.transferutility.TransferListener;
import com.amazonaws.mobileconnectors.s3.transferutility.TransferObserver;
import com.amazonaws.mobileconnectors.s3.transferutility.TransferState;
import com.amazonaws.mobileconnectors.s3.transferutility.TransferType;
import com.amazonaws.mobileconnectors.s3.transferutility.TransferUtility;
import com.amazonaws.services.s3.AmazonS3Client;
Declare Below variables in your class
private static AmazonS3Client sS3Client;
private static AWSCredentials sCredentials;
private static TransferUtility sTransferUtility;
private static TransferObserver observer;
private static List<TransferObserver> observers;
Below are configuration for downloading file from aws s3 private bucket
Step 1 : Gets an instance of CognitoCachingCredentialsProvider.
private static AWSCredentials getCredentials(String accessKey, String secretKey) {
    if (sCredentials == null) {
        sCredentials = new BasicAWSCredentials(accessKey,secretKey);
    }
    return sCredentials;
}
Step 2 : Gets an instance of the TransferUtility
public static TransferUtility getTransferUtility(String accessKey, String secretKey, Context context) {
    if (sTransferUtility == null) {
        sTransferUtility = new TransferUtility(getS3Client(accessKey, secretKey),
                context);
    }
    return sTransferUtility;
}
Step 3 : Gets an instance of a S3 client which is constructed, returns A default S3 client.proxyHost
public static AmazonS3Client getS3Client(String accessKey, String secretKey) {
    if (sS3Client == null) {
        sS3Client = new AmazonS3Client(getCredentials(accessKey, secretKey));
        sS3Client.setEndpoint({YOUR_AWS_ENDPOINT});
    }
    return sS3Client;
}
Observer to Get List of downloads in progress or we can say Gets all relevant transfers from the Transfer Service
private static void initDataObserver() {
        // Uses TransferUtility to get all previous download records.        
        observers = sTransferUtility.getTransfersWithType(TransferType.DOWNLOAD);
        TransferListener listener = new DownloadListener();
        for (TransferObserver observer : observers) {
            HashMap<String, Object> map = new HashMap<String, Object>();
            fillMap(map, observer, false);
            observer.setTransferListener(listener);

        }
    }
Fills in the map with information in the observer so that it can be used for 
further processing
public static void fillMap(Map<String, Object> map, TransferObserver observer, boolean isChecked) {
        int progress = (int) ((double) observer.getBytesTransferred() * 100 / observer
                .getBytesTotal());
        map.put("id", observer.getId());
        map.put("checked", isChecked);
        map.put("fileName", observer.getAbsoluteFilePath());
        map.put("progress", progress);
        map.put("bytes",
                getBytesString(observer.getBytesTransferred()) + "/" + getBytesString(observer.getBytesTotal()));
        map.put("state", observer.getState());
        map.put("percentage", progress + "%");
}

public static String getBytesString(long bytes) {
        // Converts number of bytes into proper scale.
        String[] quantifiers = new String[] {"KB", "MB", "GB", "TB"};
        double speedNum = bytes;
        for (int i = 0;; i++) {
            if (i >= quantifiers.length) {
                return "";
            }
            speedNum /= 1024;
            if (speedNum < 512) {
                return String.format("%.2f", speedNum) + " " + quantifiers[i];
            }
        }
    }
A TransferListener class that can listen to a download task and be notified when the 
status changes.

There are basically 3 methods of it :
1. onError() : which represents error while downloading
2. onProgressChanged() : which represents how many bytes are downloaded from total 
   no. of bytes
3. onStateChanged() : which represents changed state of downloading, states can be 
   any of below :
   
 - TransferState.IN_PROGRESS
 - TransferState.COMPLETED
 - TransferState.CANCELED
 - TransferState.FAILED
 - TransferState.PART_COMPLETED
 - TransferState.PAUSED
 - TransferState.PENDING_CANCEL
 - TransferState.PENDING_NETWORK_DISCONNECT
 - TransferState.PENDING_PAUSE
 - TransferState.RESUMED_WAITING
 - TransferState.UNKNOWN
 - TransferState.WAITING
 - TransferState.WAITING_FOR_NETWORK
private static class DownloadListener implements TransferListener {
               
       @Override        
       public void onError(int id, Exception e) {
            Log.e("Download observer", "onError: " + id, e);
            if (observers != null) {
                for (TransferObserver observer : observers) {
                    if (id == observer.getId()) {
                        Log.e("path", observer.getAbsoluteFilePath());
                        Log.e("key", observer.getKey());
                        Log.e("status", observer.getState() + "");
                    }
                }
            }
        }

        @Override        
        public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
            Log.d("Download observer", String.format("onProgressChanged: %d, total: %d, current: %d", id, bytesTotal, bytesCurrent));
        }

        @Override        
        public void onStateChanged(int id, TransferState state) {
            Log.d("Download observer", "onStateChanged: " + id + ", " + state);
            for (TransferObserver observer : observers) {
                if (id == observer.getId()) {
                    Log.e("path", observer.getAbsoluteFilePath());
                    Log.e("key status", observer.getKey() + " " + observer.getState());
                }
            }
        }
    }
Finally, After completing configuration & initializing observer, you can download file via below code lines :
public static void startDownload(Context context) {

         sTransferUtility = getTransferUtility({AWS_ACCESS_KEY_ID}, {AWS_SECRET_ACCESS_KEY}, context);
         initDataObserver();
         observer = sTransferUtility.download({AWS_BUCKET_NAME}, {YOUR_AWS_KEY}, {LOCAL_FILE_PATH});
}
You are Done!!

Comments

  1. The 12 best casinos in Portland - Mapyro
    Here 대구광역 출장마사지 at Mapyro, we 제천 출장안마 have 용인 출장마사지 a large selection of exciting 익산 출장샵 casinos in Portland. 강원도 출장안마 These include Resorts Casino and Hard Rock Casino.

    ReplyDelete

Post a Comment

Popular posts from this blog

FCM - Firebase cloud messanfing for Notification

Read sms automatically to verify OTP

Create shapes online - Android Shapes Generator