com.google.android.gms.drive.DriveFile Java Examples

The following examples show how to use com.google.android.gms.drive.DriveFile. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DeleteFileActivity.java    From android-samples with Apache License 2.0 6 votes vote down vote up
private void deleteFile(DriveFile file) {
    // [START drive_android_delete_file]
    getDriveResourceClient()
            .delete(file)
            .addOnSuccessListener(this,
                    aVoid -> {
                        showMessage(getString(R.string.file_deleted));
                        finish();
                    })
            .addOnFailureListener(this, e -> {
                Log.e(TAG, "Unable to delete file", e);
                showMessage(getString(R.string.delete_failed));
                finish();
            });
    // [END drive_android_delete_file]
}
 
Example #2
Source File: GoogleDriveClient.java    From financisto with GNU General Public License v2.0 6 votes vote down vote up
@Subscribe(threadMode = ThreadMode.BACKGROUND)
public void doRestore(DoDriveRestore event) {
    try {
        ConnectionResult connectionResult = connect();
        if (connectionResult.isSuccess()) {
            DriveFile file = Drive.DriveApi.getFile(googleApiClient, event.selectedDriveFile.driveId);
            DriveApi.DriveContentsResult contentsResult = file.open(googleApiClient, DriveFile.MODE_READ_ONLY, null).await();
            if (contentsResult.getStatus().isSuccess()) {
                DriveContents contents = contentsResult.getDriveContents();
                try {
                    DatabaseImport.createFromGoogleDriveBackup(context, db, contents).importDatabase();
                    bus.post(new DriveRestoreSuccess());
                } finally {
                    contents.discard(googleApiClient);
                }
            } else {
                handleFailure(contentsResult.getStatus());
            }
        } else {
            handleConnectionResult(connectionResult);
        }
    } catch (Exception e) {
        handleError(e);
    }
}
 
Example #3
Source File: InsertUpdateCustomPropertyActivity.java    From android-samples with Apache License 2.0 6 votes vote down vote up
private void updateCustomProperty(DriveFile file) {
    // [START drive_android_update_custom_property]
    CustomPropertyKey approvalPropertyKey =
            new CustomPropertyKey("approved", CustomPropertyKey.PUBLIC);
    CustomPropertyKey submitPropertyKey =
            new CustomPropertyKey("submitted", CustomPropertyKey.PUBLIC);
    MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                                          .setCustomProperty(approvalPropertyKey, "yes")
                                          .setCustomProperty(submitPropertyKey, "no")
                                          .build();
    Task<Metadata> updateMetadataTask =
            getDriveResourceClient().updateMetadata(file, changeSet);
    updateMetadataTask
            .addOnSuccessListener(this,
                    metadata -> {
                        showMessage(getString(R.string.custom_property_updated));
                        finish();
                    })
            .addOnFailureListener(this, e -> {
                Log.e(TAG, "Unable to update metadata", e);
                showMessage(getString(R.string.update_failed));
                finish();
            });
    // [END drive_android_update_custom_property]
}
 
Example #4
Source File: FileManager.java    From amiibo with GNU General Public License v2.0 6 votes vote down vote up
@DebugLog
private void readFileFromDrive(final MetadataBuffer meta_data, final DriveId drive_id) {
    Drive.DriveApi.getFile(_parent.getClient(), drive_id)
            .open(_parent.getClient(), DriveFile.MODE_READ_ONLY, null)
            .setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {
                @Override
                public void onResult(DriveApi.DriveContentsResult driveContentsResult) {
                    try {
                        InputStream input = driveContentsResult.getDriveContents()
                                .getInputStream();
                        String total = consumeStream(input);

                        AmiiboFile amiibo_file = AmiiboFile.fromString(total.toString());
                        _parent.onFileRead(amiibo_file);
                        if (!meta_data.isClosed()) meta_data.release();
                    } catch (IOException e) {
                        e.printStackTrace();
                        _parent.onFileRead(null);
                    }
                }
            });
}
 
Example #5
Source File: DeleteCustomPropertyActivity.java    From android-samples with Apache License 2.0 6 votes vote down vote up
private void deleteCustomProperty(DriveFile file) {
    // [START drive_android_delete_custom_property]
    CustomPropertyKey approvalPropertyKey =
            new CustomPropertyKey("approved", CustomPropertyKey.PUBLIC);
    CustomPropertyKey submitPropertyKey =
            new CustomPropertyKey("submitted", CustomPropertyKey.PUBLIC);
    MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                                          .deleteCustomProperty(approvalPropertyKey)
                                          .deleteCustomProperty(submitPropertyKey)
                                          .build();
    Task<Metadata> updateMetadataTask =
            getDriveResourceClient().updateMetadata(file, changeSet);
    updateMetadataTask
            .addOnSuccessListener(this,
                    metadata -> {
                        showMessage(getString(R.string.custom_property_deleted));
                        finish();
                    })
            .addOnFailureListener(this, e -> {
                Log.e(TAG, "Unable to update metadata", e);
                showMessage(getString(R.string.update_failed));
                finish();
            });
    // [END drive_android_delete_custom_property]
}
 
Example #6
Source File: TGDriveBrowser.java    From tuxguitar with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void getOutputStream(final TGBrowserCallBack<OutputStream> cb, final TGBrowserElement element) {
	try {
		DriveFile driveFile = ((TGDriveBrowserFile) element).getFile();
		driveFile.open(TGDriveBrowser.this.client, DriveFile.MODE_WRITE_ONLY, null).setResultCallback(new ResultCallback<DriveContentsResult>() {
			public void onResult(final DriveContentsResult result) {
				if( result.getStatus().isSuccess() ) {
					cb.onSuccess(new TGDriveBrowserOutputStream(result.getDriveContents().getOutputStream(), new Runnable() {
						public void run() {
							result.getDriveContents().commit(TGDriveBrowser.this.client, null);
						}
					}));
				} else {
					cb.handleError(new TGBrowserException(findActivity().getString(R.string.gdrive_write_file_error)));
				}
			}
		});
	} catch (Throwable e) {
		cb.handleError(e);
	}
}
 
Example #7
Source File: EditMetadataActivity.java    From android-samples with Apache License 2.0 6 votes vote down vote up
private void editMetadata(DriveFile file) {
    // [START drive_android_update_metadata]
    MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                                          .setStarred(true)
                                          .setIndexableText("Description about the file")
                                          .setTitle("A new title")
                                          .build();
    Task<Metadata> updateMetadataTask =
            getDriveResourceClient().updateMetadata(file, changeSet);
    updateMetadataTask
            .addOnSuccessListener(this,
                    metadata -> {
                        showMessage(getString(R.string.metadata_updated));
                        finish();
                    })
            .addOnFailureListener(this, e -> {
                Log.e(TAG, "Unable to update metadata", e);
                showMessage(getString(R.string.update_failed));
                finish();
            });
    // [END drive_android_update_metadata]
}
 
Example #8
Source File: RetrieveMetadataActivity.java    From android-samples with Apache License 2.0 6 votes vote down vote up
private void retrieveMetadata(final DriveFile file) {
    // [START drive_android_retrieve_metadata]
    Task<Metadata> getMetadataTask = getDriveResourceClient().getMetadata(file);
    getMetadataTask
            .addOnSuccessListener(this,
                    metadata -> {
                        showMessage(getString(
                                R.string.metadata_retrieved, metadata.getTitle()));
                        finish();
                    })
            .addOnFailureListener(this, e -> {
                Log.e(TAG, "Unable to retrieve metadata", e);
                showMessage(getString(R.string.read_failed));
                finish();
            });
    // [END drive_android_retrieve_metadata]
}
 
Example #9
Source File: EditContentsAsyncTask.java    From ToDay with MIT License 6 votes vote down vote up
@Override
protected Boolean doInBackgroundConnected(EditContentParams... args) {
    DriveFile file = args[0].getFileToWrite();
    String dataToWrite = args[0].getDataToWrite();

    try {
        DriveApi.DriveContentsResult driveContentsResult = file.open(
                getGoogleApiClient(), DriveFile.MODE_WRITE_ONLY, null).await();
        if (!driveContentsResult.getStatus().isSuccess()) {
            return false;
        }
        DriveContents driveContents = driveContentsResult.getDriveContents();
        OutputStream outputStream = driveContents.getOutputStream();
        outputStream.write(dataToWrite.getBytes());
        com.google.android.gms.common.api.Status status =
                driveContents.commit(getGoogleApiClient(), null).await();
        return status.getStatus().isSuccess();
    } catch (IOException e) {
        AppUtils.showMessage(context,"Failed to write data to file.");
    }
    return false;
}
 
Example #10
Source File: ListenChangeEventsForFilesActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Toggles the subscription status. If there is no selected file, returns
 * immediately.
 */
private void toggle() {
    if (mSelectedFileId == null) {
        return;
    }
    stopTimer();
    DriveFile file = mSelectedFileId.asDriveFile();
    if (!mIsSubscribed) {
        Log.d(TAG, "Starting to listen to the file changes.");
        mIsSubscribed = true;
        mCountDownTimer = new TickleTimer(30000 /* 30 seconds total */,
                1000 /* tick every 1 second */ );
        mCountDownTimer.start();
        // [START drive_android_add_change_listener]
        getDriveResourceClient()
                .addChangeListener(file, changeListener)
                .addOnSuccessListener(this, listenerToken -> mChangeListenerToken = listenerToken);
        // [END drive_android_add_change_listener]
    } else {
        Log.d(TAG, "Stopping to listen to the file changes.");
        mIsSubscribed = false;
        // [START drive_android_remove_change_listener]
        getDriveResourceClient().removeChangeListener(mChangeListenerToken);
        // [END drive_android_remove_change_listener]
    }
    refresh();
}
 
Example #11
Source File: DriveSyncService.java    From Passbook with Apache License 2.0 5 votes vote down vote up
@Override
public void send(byte[] data) {
    if(data != null) {
        mData = data;
        if (mDriveResourceClient == null) {
            mListener.onSyncFailed(CA.AUTH);
            return;
        }
        Task<DriveContents> contentsTask;
        if (mDriveId == null) {
            contentsTask = mDriveResourceClient.getAppFolder()
                    .continueWithTask(t -> {
                        MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                                .setTitle(SAVED_DATA)
                                .setMimeType("application/bin")
                                .build();
                        DriveFile file = mDriveResourceClient.createFile(t.getResult(), changeSet, null).getResult();
                        mDriveId = file.getDriveId();
                        return mDriveResourceClient.openFile(file, DriveFile.MODE_WRITE_ONLY);
                    });
        } else {
            contentsTask = mDriveResourceClient.openFile(mDriveId.asDriveFile(), DriveFile.MODE_WRITE_ONLY);
        }
        contentsTask
                .continueWithTask(t -> {
                    DriveContents contents = t.getResult();
                    OutputStream outputStream = contents.getOutputStream();
                    outputStream.write(mData);
                    return mDriveResourceClient.commitContents(contents, null);
                })
                .addOnFailureListener(e -> mListener.onSyncFailed(CA.DATA_SENT))
                .addOnSuccessListener(s -> mListener.onSyncProgress(CA.DATA_SENT));
    }
}
 
Example #12
Source File: RetrieveContentsActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
private void retrieveContents(DriveFile file) {
    // [START drive_android_open_file]
    Task<DriveContents> openFileTask =
            getDriveResourceClient().openFile(file, DriveFile.MODE_READ_ONLY);
    // [END drive_android_open_file]
    // [START drive_android_read_contents]
    openFileTask
            .continueWithTask(task -> {
                DriveContents contents = task.getResult();
                // Process contents...
                // [START_EXCLUDE]
                // [START drive_android_read_as_string]
                try (BufferedReader reader = new BufferedReader(
                             new InputStreamReader(contents.getInputStream()))) {
                    StringBuilder builder = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        builder.append(line).append("\n");
                    }
                    showMessage(getString(R.string.content_loaded));
                    mFileContents.setText(builder.toString());
                }
                // [END drive_android_read_as_string]
                // [END_EXCLUDE]
                // [START drive_android_discard_contents]
                Task<Void> discardTask = getDriveResourceClient().discardContents(contents);
                // [END drive_android_discard_contents]
                return discardTask;
            })
            .addOnFailureListener(e -> {
                // Handle failure
                // [START_EXCLUDE]
                Log.e(TAG, "Unable to read contents", e);
                showMessage(getString(R.string.read_failed));
                finish();
                // [END_EXCLUDE]
            });
    // [END drive_android_read_contents]
}
 
Example #13
Source File: SubscribeChangeEventsForFilesActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Toggles the subscription status. If there is no selected file, returns
 * immediately.
 */
private void toggle() {
    if (mSelectedFileId == null) {
        return;
    }
    stopTimer();
    DriveFile file = mSelectedFileId.asDriveFile();
    if (!mIsSubscribed) {
        Log.d(TAG, "Starting to listen to the file changes.");
        mIsSubscribed = true;
        mCountDownTimer = new TickleTimer(30000 /* 30 seconds total */,
                1000 /* tick every 1 second */);
        mCountDownTimer.start();
        // [START drive_android_add_change_subscription]
        getDriveResourceClient().addChangeSubscription(file).addOnSuccessListener(
                aVoid -> showMessage(getString(R.string.subscribed)));
        // [END drive_android_add_change_subscription]
    } else {
        Log.d(TAG, "Stopping to listen to the file changes.");
        mIsSubscribed = false;
        // [START drive_android_remove_change_listener]
        getDriveResourceClient().removeChangeSubscription(file).addOnSuccessListener(
                aVoid -> showMessage(getString(R.string.unsubscribed)));
        // [END drive_android_remove_change_listener]
    }
    refresh();
}
 
Example #14
Source File: RewriteContentsActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
private void rewriteContents(DriveFile file) {
    // [START drive_android_open_for_write]
    Task<DriveContents> openTask =
            getDriveResourceClient().openFile(file, DriveFile.MODE_WRITE_ONLY);
    // [END drive_android_open_for_write]
    // [START drive_android_rewrite_contents]
    openTask.continueWithTask(task -> {
        DriveContents driveContents = task.getResult();
        try (OutputStream out = driveContents.getOutputStream()) {
            out.write("Hello world".getBytes());
        }
        // [START drive_android_commit_content]
        Task<Void> commitTask =
                getDriveResourceClient().commitContents(driveContents, null);
        // [END drive_android_commit_content]
        return commitTask;
    })
            .addOnSuccessListener(this,
                    aVoid -> {
                        showMessage(getString(R.string.content_updated));
                        finish();
                    })
            .addOnFailureListener(this, e -> {
                Log.e(TAG, "Unable to update contents", e);
                showMessage(getString(R.string.content_update_failed));
                finish();
            });
    // [END drive_android_rewrite_contents]
}
 
Example #15
Source File: MainActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an empty file in the current folder.
 */
private void createFile() {
    setUiInteractionsEnabled(false);
    int fileCount = mFileFolderAdapter.getCount();
    MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
            .setTitle("sample file " + (fileCount + 1))
            .setMimeType("text/plain")
            .build();
    DriveFolder driveFolder = mNavigationPath.peek().asDriveFolder();
    Task<DriveFile> createFileTask =
            mDriveResourceClient.createFile(driveFolder, changeSet, null);
    Task<Void> updateTask = updateUiAfterTask(createFileTask);
    handleTaskError(updateTask, R.string.unexpected_error);
}
 
Example #16
Source File: MainActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the grocery list items.
 */
private Task<Void> loadContents(DriveFile file) {
    mGroceryListFile = file;
    Task<DriveContents> loadTask =
            getDriveResourceClient().openFile(file, DriveFile.MODE_READ_ONLY);
    return loadTask.continueWith(task -> {
        Log.d(TAG, "Reading file contents.");
        mDriveContents = task.getResult();
        InputStream inputStream = mDriveContents.getInputStream();
        String groceryListStr = ConflictUtil.getStringFromInputStream(inputStream);

        mEditText.setText(groceryListStr);
        return null;
    });
}
 
Example #17
Source File: MainActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
private Task<DriveFile> createNewFile() {
    Log.d(TAG, "Creating new grocery list.");
    return getDriveResourceClient().getRootFolder().continueWithTask(
            task -> {
                DriveFolder folder = task.getResult();
                MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                                                      .setTitle(getResources().getString(
                                                              R.string.groceryListFileName))
                                                      .setMimeType("text/plain")
                                                      .build();

                return getDriveResourceClient().createFile(folder, changeSet, null);
            });
}
 
Example #18
Source File: PinFileActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
private void pinFile(final DriveFile file) {
    // [START drive_android_pin_file]
    Task<Metadata> pinFileTask = getDriveResourceClient().getMetadata(file).continueWithTask(
            task -> {
                Metadata metadata = task.getResult();
                if (!metadata.isPinnable()) {
                    showMessage(getString(R.string.file_not_pinnable));
                    return Tasks.forResult(metadata);
                }
                if (metadata.isPinned()) {
                    showMessage(getString(R.string.file_already_pinned));
                    return Tasks.forResult(metadata);
                }
                MetadataChangeSet changeSet =
                        new MetadataChangeSet.Builder().setPinned(true).build();
                return getDriveResourceClient().updateMetadata(file, changeSet);
            });
    // [END drive_android_pin_file]
    // [START drive_android_pin_file_completion]
    pinFileTask
            .addOnSuccessListener(this,
                    metadata -> {
                        showMessage(getString(R.string.metadata_updated));
                        finish();
                    })
            .addOnFailureListener(this, e -> {
                Log.e(TAG, "Unable to update metadata", e);
                showMessage(getString(R.string.update_failed));
                finish();
            });
    // [END drive_android_pin_file_completion]
}
 
Example #19
Source File: DriveSettingsManager.java    From CumulusTV with MIT License 5 votes vote down vote up
@Override
protected Boolean doInBackground(Object... args) {
    DriveFile file = (DriveFile) args[0];
    String data = (String) args[1];
    try {
        DriveApi.DriveContentsResult driveContentsResult = file.open(
                mGoogleApiClient, DriveFile.MODE_WRITE_ONLY, null).await();
        if (!driveContentsResult.getStatus().isSuccess()) {
            return false;
        }
        driveContents = driveContentsResult.getDriveContents();
        OutputStream outputStream = driveContents.getOutputStream();
        outputStream.write(data.getBytes());
        com.google.android.gms.common.api.Status status =
                driveContents.commit(mGoogleApiClient, null).await();
        if(mGoogleDriveListener != null) {
            Handler h = new Handler(Looper.getMainLooper()) {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    mGoogleDriveListener.onActionFinished(false);
                }
            };
            h.sendEmptyMessage(0);
        }
        return status.getStatus().isSuccess();
    } catch (IOException e) {
        if (DEBUG) {
            Log.e(TAG, "IOException while appending to the output stream", e);
        }
    }
    return false;
}
 
Example #20
Source File: DriveSettingsManager.java    From CumulusTV with MIT License 5 votes vote down vote up
/**
 * Writes some data to a Google Drive file, this can get from a preference
 * @param driveId The id of the file to be written to
 * @param data The string of data that should be written
 */
public void writeToGoogleDrive(DriveId driveId, String data) {
    DriveFile file = Drive.DriveApi.getFile(mGoogleApiClient, driveId);
    if (DEBUG) {
        Log.d(TAG, "Writing to " + driveId + " -> " + data);
    }
    new EditGoogleDriveAsyncTask(mContext).execute(file, data);
}
 
Example #21
Source File: DriveLayer.java    From Drive-Database-Sync with Apache License 2.0 5 votes vote down vote up
/**
 * {@link QuerierResultCallback} called when a DriveFile with the queried filename is found
 * @param m the {@link Metadata} for the found DriveFile
 */
@Override
public void onQuerierResult(Metadata m) {
    if (debug) {
        Log.d("DriveLayer", "Got Query results");
    }

    callback.onMetaDataReceived(m);

    DriveFio driveFio = new DriveFio(this);
    DriveFile driveFile = driveFio.getDriveFileFromMetadata(mDriveClient, m);
    driveFio.loadDriveFile(mDriveClient, driveFile, callback.openModeWriteable());
}
 
Example #22
Source File: RetrieveDriveFileContentsAsyncTask.java    From faceswap with Apache License 2.0 5 votes vote down vote up
@Override
protected String doInBackgroundConnected(DriveId... params) {
    String state = null;
    DriveFile file = params[0].asDriveFile();
    DriveApi.DriveContentsResult driveContentsResult =
            file.open(getGoogleApiClient(), DriveFile.MODE_READ_ONLY, null).await();
    if (!driveContentsResult.getStatus().isSuccess()) {
        return null;
    }
    DriveContents driveContents = driveContentsResult.getDriveContents();
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(driveContents.getInputStream()));
    StringBuilder builder = new StringBuilder();
    String line;
    try {
        while ((line = reader.readLine()) != null) {
            builder.append(line);
            builder.append("\n");
        }
        state = builder.toString();
        reader.close();
    } catch (IOException e) {
        Log.e(TAG, "IOException while reading from the stream", e);
    }
    driveContents.discard(getGoogleApiClient());
    String validState=UIUtils.stripMagicSequence(state);
    return validState;
}
 
Example #23
Source File: DriveSyncService.java    From Passbook with Apache License 2.0 4 votes vote down vote up
@Override
public void read() {
    if (mDriveResourceClient == null) {
        mListener.onSyncFailed(CA.CONNECTION);
    }
    final Task<DriveFolder> appFolderTask = mDriveResourceClient.getAppFolder();
    final Query query = new Query.Builder().build();
    appFolderTask.continueWithTask(t -> mDriveResourceClient.queryChildren(t.getResult(), query))
            .continueWithTask(t -> {
                Task<DriveContents> contentsTask = null;
                for (Metadata metadata : t.getResult()) {
                    if (SAVED_DATA.equalsIgnoreCase(metadata.getTitle())) {
                        mDriveId = metadata.getDriveId();
                        contentsTask= mDriveResourceClient.openFile(mDriveId.asDriveFile(), DriveFile.MODE_READ_ONLY);
                        break;
                    }
                }
                if (contentsTask == null) {
                    return mDriveResourceClient.createContents();
                }
                return contentsTask;
            })
            .addOnSuccessListener(c -> {
                try {
                    InputStream fis = c.getInputStream();
                    if (fis.available() < 1) {
                        throw new IOException();
                    }
                    mData = new byte[fis.available()];
                    int totalBytesRead = fis.read(mData);
                    fis.close();
                    if (totalBytesRead < mData.length) {
                        throw new IOException();
                    }
                    mListener.onSyncProgress(CA.DATA_RECEIVED);

                } catch (IllegalStateException | IOException e) {
                    Log.e(LOG_TAG, "read: ", e.getCause());
                    mListener.onSyncFailed(CA.NO_DATA);
                }
            })
            .addOnFailureListener(f -> mListener.onSyncFailed(CA.NO_DATA));
}
 
Example #24
Source File: TGDriveBrowserFile.java    From tuxguitar with GNU Lesser General Public License v2.1 4 votes vote down vote up
public DriveFile getFile() {
	return file;
}
 
Example #25
Source File: TGDriveBrowserFile.java    From tuxguitar with GNU Lesser General Public License v2.1 4 votes vote down vote up
public TGDriveBrowserFile(TGDriveBrowserFolder parent, DriveFile file, String name) {
	this.parent = parent;
	this.name = name;
	this.file = file;
}
 
Example #26
Source File: AppendContentsActivity.java    From android-samples with Apache License 2.0 4 votes vote down vote up
private void appendContents(DriveFile file) {
    // [START drive_android_open_for_append]
    Task<DriveContents> openTask =
            getDriveResourceClient().openFile(file, DriveFile.MODE_READ_WRITE);
    // [END drive_android_open_for_append]
    // [START drive_android_append_contents]
    openTask.continueWithTask(task -> {
        DriveContents driveContents = task.getResult();
        ParcelFileDescriptor pfd = driveContents.getParcelFileDescriptor();
        long bytesToSkip = pfd.getStatSize();
        try (InputStream in = new FileInputStream(pfd.getFileDescriptor())) {
            // Skip to end of file
            while (bytesToSkip > 0) {
                long skipped = in.skip(bytesToSkip);
                bytesToSkip -= skipped;
            }
        }
        try (OutputStream out = new FileOutputStream(pfd.getFileDescriptor())) {
            out.write("Hello world".getBytes());
        }
        // [START drive_android_commit_contents_with_metadata]
        MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                                              .setStarred(true)
                                              .setLastViewedByMeDate(new Date())
                                              .build();
        Task<Void> commitTask =
                getDriveResourceClient().commitContents(driveContents, changeSet);
        // [END drive_android_commit_contents_with_metadata]
        return commitTask;
    })
        .addOnSuccessListener(this,
                aVoid -> {
                    showMessage(getString(R.string.content_updated));
                    finish();
                })
        .addOnFailureListener(this, e -> {
            Log.e(TAG, "Unable to update contents", e);
            showMessage(getString(R.string.content_update_failed));
            finish();
        });
    // [END drive_android_append_contents]
}
 
Example #27
Source File: RemoteBackup.java    From Database-Backup-Restore with Apache License 2.0 4 votes vote down vote up
private void retrieveContents(DriveFile file) {

        //DB Path
        final String inFileName = activity.getDatabasePath(DATABASE_NAME).toString();

        Task<DriveContents> openFileTask = mDriveResourceClient.openFile(file, DriveFile.MODE_READ_ONLY);

        openFileTask
                .continueWithTask(task -> {
                    DriveContents contents = task.getResult();
                    try {
                        ParcelFileDescriptor parcelFileDescriptor = contents.getParcelFileDescriptor();
                        FileInputStream fileInputStream = new FileInputStream(parcelFileDescriptor.getFileDescriptor());

                        // Open the empty db as the output stream
                        OutputStream output = new FileOutputStream(inFileName);

                        // Transfer bytes from the inputfile to the outputfile
                        byte[] buffer = new byte[1024];
                        int length;
                        while ((length = fileInputStream.read(buffer)) > 0) {
                            output.write(buffer, 0, length);
                        }

                        // Close the streams
                        output.flush();
                        output.close();
                        fileInputStream.close();
                        Toast.makeText(activity, "Import completed", Toast.LENGTH_SHORT).show();

                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(activity, "Error on import", Toast.LENGTH_SHORT).show();
                    }
                    return mDriveResourceClient.discardContents(contents);

                })
                .addOnFailureListener(e -> {
                    Log.e(TAG, "Unable to read contents", e);
                    Toast.makeText(activity, "Error on import", Toast.LENGTH_SHORT).show();
                });
    }
 
Example #28
Source File: ConflictResolver.java    From android-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Initiate the resolution process by connecting the GoogleApiClient.
 */
void resolve() {
    // [START drive_android_resolve_conflict]
    // A new DriveResourceClient should be created to handle each new CompletionEvent since each
    // event is tied to a specific user account. Any DriveFile action taken must be done using
    // the correct account.
    GoogleSignInOptions.Builder signInOptionsBuilder =
            new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestScopes(Drive.SCOPE_FILE)
                    .requestScopes(Drive.SCOPE_APPFOLDER);
    if (mConflictedCompletionEvent.getAccountName() != null) {
        signInOptionsBuilder.setAccountName(mConflictedCompletionEvent.getAccountName());
    }
    GoogleSignInClient signInClient =
            GoogleSignIn.getClient(mContext, signInOptionsBuilder.build());
    signInClient.silentSignIn()
            .continueWith(mExecutorService,
                    (Continuation<GoogleSignInAccount, Void>) signInTask -> {
                        mDriveResourceClient = Drive.getDriveResourceClient(
                                mContext, signInTask.getResult());
                        mBaseContent = ConflictUtil.getStringFromInputStream(
                                mConflictedCompletionEvent.getBaseContentsInputStream());
                        mModifiedContent = ConflictUtil.getStringFromInputStream(
                                mConflictedCompletionEvent
                                        .getModifiedContentsInputStream());
                        return null;
                    })
            .continueWithTask(mExecutorService,
                    task -> {
                        DriveId driveId = mConflictedCompletionEvent.getDriveId();
                        return mDriveResourceClient.openFile(
                                driveId.asDriveFile(), DriveFile.MODE_READ_ONLY);
                    })
            .continueWithTask(mExecutorService,
                    task -> {
                        mDriveContents = task.getResult();
                        InputStream serverInputStream = task.getResult().getInputStream();
                        mServerContent =
                                ConflictUtil.getStringFromInputStream(serverInputStream);
                        return mDriveResourceClient.reopenContentsForWrite(mDriveContents);
                    })
            .continueWithTask(mExecutorService,
                    task -> {
                        DriveContents contentsForWrite = task.getResult();
                        mResolvedContent = ConflictUtil.resolveConflict(
                                mBaseContent, mServerContent, mModifiedContent);

                        OutputStream outputStream = contentsForWrite.getOutputStream();
                        try (Writer writer = new OutputStreamWriter(outputStream)) {
                            writer.write(mResolvedContent);
                        }

                        // It is not likely that resolving a conflict will result in another
                        // conflict, but it can happen if the file changed again while this
                        // conflict was resolved. Since we already implemented conflict
                        // resolution and we never want to miss user data, we commit here
                        // with execution options in conflict-aware mode (otherwise we would
                        // overwrite server content).
                        ExecutionOptions executionOptions =
                                new ExecutionOptions.Builder()
                                        .setNotifyOnCompletion(true)
                                        .setConflictStrategy(
                                                ExecutionOptions
                                                        .CONFLICT_STRATEGY_KEEP_REMOTE)
                                        .build();

                        // Commit resolved contents.
                        MetadataChangeSet modifiedMetadataChangeSet =
                                mConflictedCompletionEvent.getModifiedMetadataChangeSet();
                        return mDriveResourceClient.commitContents(contentsForWrite,
                                modifiedMetadataChangeSet, executionOptions);
            })
            .addOnSuccessListener(aVoid -> {
                mConflictedCompletionEvent.dismiss();
                Log.d(TAG, "resolved list");
                sendResult(mModifiedContent);
            })
            .addOnFailureListener(e -> {
                // The contents cannot be reopened at this point, probably due to
                // connectivity, so by snoozing the event we will get it again later.
                Log.d(TAG, "Unable to write resolved content, snoozing completion event.",
                        e);
                mConflictedCompletionEvent.snooze();
                if (mDriveContents != null) {
                    mDriveResourceClient.discardContents(mDriveContents);
                }
            });
    // [END drive_android_resolve_conflict]
}
 
Example #29
Source File: EditContentParams.java    From ToDay with MIT License 4 votes vote down vote up
public EditContentParams(String dataToWrite, DriveFile fileToWrite) {
    this.dataToWrite = dataToWrite;
    this.fileToWrite = fileToWrite;
}
 
Example #30
Source File: EditContentParams.java    From ToDay with MIT License 4 votes vote down vote up
public DriveFile getFileToWrite() {
    return fileToWrite;
}