@Override public synchronized void onError(final int id, final Exception ex) { final ContentProgressListener listener = progressListeners.get(id); final TransferObserver observer = transfersInProgress.get(id); Log.d(LOG_TAG, ex.getMessage(), ex); if (listener != null) { ThreadUtils.runOnUiThread(new Runnable() { @Override public void run() { listener.onError(getRelativeFilePath(observer.getAbsoluteFilePath()), ex); } }); } // The transfer is not cleaned up here, since it is handled when // the state changes to failed above in onStateChanged(). }
/** * @param key the S3 Key. Note that the value provided as 'bucketPath' in * {@link #provideCredentials(String, String, String, String, String)} * will be prepended to this value * @param contents the file contents to upload * @param metadata any additional metadata, like caching headers */ private void uploadFile(@NonNull String key, @NonNull File contents, @NonNull ObjectMetadata metadata) { String absoluteKey = new File(bucketPath, key).getPath(); TransferObserver observer = transferUtility.upload( bucket, absoluteKey, contents, metadata ); // TODO: destination URL via S3 SDK? String destinationUrl = String.format("https://%s.s3.amazonaws.com/%s", bucket, absoluteKey); activeUploadMap.put(observer.getId(), new ActiveUpload(contents, destinationUrl)); observer.setTransferListener(this); Timber.d("Beginning upload of %s to %s", contents.getAbsolutePath(), destinationUrl); }
/** * Gets all relevant transfers from the Transfer Service for populating the * UI */ private void initData() { transferRecordMaps.clear(); // Use TransferUtility to get all upload transfers. observers = transferUtility.getTransfersWithType(TransferType.UPLOAD); TransferListener listener = new UploadListener(); for (TransferObserver observer : observers) { // For each transfer we will will create an entry in // transferRecordMaps which will display // as a single row in the UI HashMap<String, Object> map = new HashMap<String, Object>(); Util.fillMap(map, observer, false); transferRecordMaps.add(map); // Sets listeners to in progress transfers if (TransferState.WAITING.equals(observer.getState()) || TransferState.WAITING_FOR_NETWORK.equals(observer.getState()) || TransferState.IN_PROGRESS.equals(observer.getState())) { observer.setTransferListener(listener); } } simpleAdapter.notifyDataSetChanged(); }
private void beginUpload(String filePath) { if (filePath == null) { Toast.makeText(this, "Could not find the filepath of the selected file", Toast.LENGTH_LONG).show(); return; } File file = new File(filePath); TransferObserver observer = transferUtility.upload(Constants.BUCKET_NAME, file.getName(), file); /* * Note that usually we set the transfer listener after initializing the * transfer. However it isn't required in this sample app. The flow is * click upload button -> start an activity for image selection * startActivityForResult -> onActivityResult -> beginUpload -> onResume * -> set listeners to in progress transfers. */ // observer.setTransferListener(new UploadListener()); }
/** * Gets all relevant transfers from the Transfer Service for populating the * UI */ private void initData() { transferRecordMaps.clear(); // Uses TransferUtility to get all previous download records. observers = transferUtility.getTransfersWithType(TransferType.DOWNLOAD); TransferListener listener = new DownloadListener(); for (TransferObserver observer : observers) { HashMap<String, Object> map = new HashMap<String, Object>(); Util.fillMap(map, observer, false); transferRecordMaps.add(map); // Sets listeners to in progress transfers if (TransferState.WAITING.equals(observer.getState()) || TransferState.WAITING_FOR_NETWORK.equals(observer.getState()) || TransferState.IN_PROGRESS.equals(observer.getState())) { observer.setTransferListener(listener); } } simpleAdapter.notifyDataSetChanged(); }
private void beginDownload(String key) { // Location to download files from S3 to. You can choose any accessible // file. File file = new File(Environment.getExternalStorageDirectory().toString() + "/" + key); // Initiate the download TransferObserver observer = transferUtility.download(Constants.BUCKET_NAME, key, file); /* * Note that usually we set the transfer listener after initializing the * transfer. However it isn't required in this sample app. The flow is * click upload button -> start an activity for image selection * startActivityForResult -> onActivityResult -> beginUpload -> onResume * -> set listeners to in progress transfers. */ // observer.setTransferListener(new DownloadListener()); }
private TransferObserver startTransfer(final String filePath, final long fileSize, final ContentProgressListener listener) { final TransferObserver observer; final File localTransferFile = new File(localTransferPath + filePath); final String s3Key = s3DirPrefix + filePath; final int transferId; synchronized (this) { sizeTransferring += fileSize; observer = transferUtility.download(bucket, s3Key, localTransferFile); transferId = observer.getId(); // Set the progress listener for the transfer progressListeners.put(transferId, listener); transfersInProgress.put(transferId, observer); managedFilesToTransfers.put(filePath, transferId); } // Set our self to listen for progress and state changes. This should // not be set until the observer has been added to the progressListeners // data structure. // (This does not stop listening onPause and resume listening onResume; // instead it stays listening until the download succeeds or fails.) observer.setTransferListener(this); // Transfers get created in the waiting state, which we will miss since we can't set // our listener until we have a transfer ID to associate it with, and even if we // could it appear that the initial creation of the transfer causes onStateChanged // to be called. onStateChanged(transferId, observer.getState()); return observer; }
/** * Sets the progress listener for a given s3Key being transferred. * @param relativeFilePath the relative path and file name. * @param listener the progress listener. */ public synchronized void setProgressListener(final String relativeFilePath, final ContentProgressListener listener) { final Integer transferId = managedFilesToTransfers.get(relativeFilePath); if (transferId != null) { if (listener == null) { progressListeners.remove(transferId); return; } final TransferObserver observer = transfersInProgress.get(transferId); if (observer != null) { final ContentProgressListener currentListener = progressListeners.get(transferId); progressListeners.put(transferId, listener); if (currentListener != listener) { observer.refresh(); final TransferState transferState = observer.getState(); if (transferState == TransferState.WAITING || transferState == TransferState.WAITING_FOR_NETWORK || transferState == TransferState.RESUMED_WAITING) { ThreadUtils.runOnUiThread(new Runnable() { @Override public void run() { onStateChanged(transferId, transferState); } }); } } } } else { Log.w(LOG_TAG, String.format("Attempt to set progress listener for file '%s'," + " but no transfer is in progress for that file.", relativeFilePath)); } }
private synchronized TransferState getTransferState(final String relativeFilePath) { final Integer transferId = managedFilesToTransfers.get(relativeFilePath); if (transferId == null) { return null; } final TransferObserver observer = transfersInProgress.get(transferId); observer.refresh(); return observer.getState(); }
/** * Cleans up all accounting data structures related to a transfer. Should be called from a * context that is synchronized on this object. * @param observer the transfer observer. */ private synchronized void cleanUpTransfer(final TransferObserver observer) { final int transferId = observer.getId(); final String relativePath = getRelativeFilePath(observer.getAbsoluteFilePath()); observer.cleanTransferListener(); transfersInProgress.remove(transferId); managedFilesToTransfers.remove(relativePath); transferUtility.deleteTransferRecord(transferId); progressListeners.remove(transferId); }
@Override public synchronized void onProgressChanged(final int id, final long bytesCurrent, final long bytesTotal) { final TransferObserver observer = transfersInProgress.get(id); if (observer == null) { // Logging at debug level since the on progress changed update frequently happens // after the state has already changed to complete. Log.d(LOG_TAG, String.format("Received progress update for id(%d), but transfer not in progress.", id)); return; } final String filePath = getRelativeFilePath(observer.getAbsoluteFilePath()); final ContentProgressListener listener = progressListeners.get(id); final long maxCacheSize = localContentCache.getMaxCacheSize(); final boolean isPinned = localContentCache.shouldPinFile(filePath); if (!isPinned && bytesTotal > maxCacheSize) { // cancel the transfer transferUtility.cancel(id); cleanUpTransfer(observer); } if (listener != null) { ThreadUtils.runOnUiThread(new Runnable() { @Override public void run() { if (!isPinned && bytesTotal > maxCacheSize) { listener.onError(filePath, new IllegalStateException(String.format( "Cancelled due to transfer size %s exceeds max cache size of %s", StringFormatUtils.getBytesString(bytesTotal, true), StringFormatUtils.getBytesString(maxCacheSize, true)))); } else { listener.onProgressUpdate(filePath, false, bytesCurrent, bytesTotal); } } }); } }
private void transferFile(File compressedFile, String parent, TransferListenerAdapter transferListener) { String filename = getFilename(compressedFile, parent); transferListener.setFilename(filename); transferListener.setBucket(context.getString(R.string.amazon_s3_bucket_id)); TransferObserver observer = AmazonServicesManager.getTransferUtility() .upload(AmazonServicesManager.BUCKET_ID, filename, compressedFile); transfersRetained.add(transferListener); observer.setTransferListener(transferListener); }
protected void upload(){ mProgressCallback.setExporting(true); init(); mProgressCallback.showProgress(ProgressUpdateCallback.UPLOAD); TransferObserver observer = mTransferUtility.upload( mCtx.getResources().getString(R.string.door43_bucket), /* The bucket to upload to */ mZipFile.getName(), /* The key for the uploaded object */ mZipFile /* The file where the data to upload exists */ ); observer.setTransferListener(mListener); }
@Override protected void onPause() { super.onPause(); // Clear transfer listeners to prevent memory leak, or // else this activity won't be garbage collected. if (observers != null && !observers.isEmpty()) { for (TransferObserver observer : observers) { observer.cleanTransferListener(); } } }
private void updateList() { TransferObserver observer = null; HashMap<String, Object> map = null; for (int i = 0; i < observers.size(); i++) { observer = observers.get(i); map = transferRecordMaps.get(i); Util.fillMap(map, observer, i == checkedIndex); } simpleAdapter.notifyDataSetChanged(); }
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 + "%"); }
private synchronized void deRegisterObservers() { for (final TransferObserver observer : transfersInProgress.values()) { observer.cleanTransferListener(); } }
/** * Uploads the file to the external storage provider */ public static void uploadFile(String key, File file, TransferListener listener) { final TransferObserver uploadObserver = sTransferUtility.upload(AWS_S3_BUCKETNAME, key, file); uploadObserver.setTransferListener(listener); }