401 response when athenticating via Service Account and OAuth2 to GoogleDrive - google-drive-api

I seem to have hit a wall trying to get a Java application to list of files stored in my GoogleDrive folder. The
I have a project setup in the Developer Console.
I have enabled for that project the Drive API
I have create Auth credentials for a Service Account - and am using the P12 key produced.
My code looks like this :
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.CredentialRefreshListener;
import com.google.api.client.auth.oauth2.TokenErrorResponse;
import com.google.api.client.auth.oauth2.TokenResponse;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;
public class GoogleDriveTest {
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = new JacksonFactory() ;
/** instance of the HTTP transport. */
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport() ;
/** Global instance of the Google Drive - the first connect will initialize */
private static Drive drive;
/*
* instance variables
*/
private String accessToken ;
public static void main(String[] args) throws GeneralSecurityException, IOException {
String CLIENTID = "XXXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX#developer.gserviceaccount.com" ;
String CLIENTUSER = "XXXXXXXX#gmail.com" ;
String P2FILE = "random/src/main/resources/test.p12" ;
try {
GoogleCredential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(CLIENTID)
.setServiceAccountScopes(Collections.singleton(DriveScopes.DRIVE_FILE))
.setServiceAccountPrivateKeyFromP12File(new java.io.File(P2FILE))
.setServiceAccountUser(CLIENTUSER)
.addRefreshListener(new CredentialRefreshListener() {
#Override
public void onTokenResponse(
Credential credential,
TokenResponse tokenResponse) throws IOException {
String token = tokenResponse.getAccessToken();
System.out.println("GOOGLEDRIVE token refreshed " + tokenResponse.getTokenType() + " successfully");
}
#Override
public void onTokenErrorResponse(
Credential credential,
TokenErrorResponse tokenErrorResponse) throws IOException {
System.out.println("GOOGLEDRIVE token refresh failure : " + tokenErrorResponse);
}
})
.build();
/*
* set up the global Drive instance
*/
drive = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName("API Project").build();
/*
* output results
*/
Drive.Files.List fileRequest = drive.files().list() ;
FileList afiles = fileRequest.execute() ;
List<File> bFiles = afiles.getItems() ;
for(File file : bFiles) {
System.out.println(file.getTitle()) ;
}
}
catch (GeneralSecurityException | IOException e) {
e.printStackTrace();
}
}
}
But the output I see is this :
GOOGLEDRIVE token refresh failure : null
com.google.api.client.auth.oauth2.TokenResponseException: 401 Unauthorized
at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:105)
at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287)
at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:384)
at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489)
at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:217)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:859)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
at GoogleDriveTest.main(GoogleDriveTest.java:81)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Process finished with exit code 0
Can anyone provide some pointers on Service Account access to Google Drive and what I might be doing wrong here ?
As the Service Account is created under my Google Account (XXXXXXXX#gmail.com) I assumed it would have access to the Drive once the API was enabled.
I have seen other posts about granting access to Service Accounts to a domain account via an admin console - but my account is a plain / standard google account. I'm not even sure what a domain account is !
All help would be greatly appreciated.

Related

Lotus Notes Agent: java.io.IOException: Access is denied

I have a java agent that will list all the files from Google Drive using the api provided from google developer (https://developers.google.com/drive/api/v3/quickstart/java).
However, the agent is having a "Access is denied" error when trying to create the "tokens" folder from "C:\Program Files (x86)\IBM\Notes\framework" directory.
I have created the "tokens" folder manually but the error still occured.
I have put all the required jar files in "/jvm/lib/ext" and updated the java policy on my local as follows:
// custom java security policy, to allow external jar file access
grant { permission java.util.PropertyPermission "http.keepAlive", "read, write"; };
grant { permission java.security.AllPermission; }
My actual agent code
private static final String APPLICATION_NAME = "Google Drive API Java Quickstart";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final String TOKENS_DIRECTORY_PATH = "tokens";
/**
* Global instance of the scopes required by this quickstart.
* If modifying these scopes, delete your previously saved tokens/ folder.
*/
private static final List<String> SCOPES = Collections.singletonList(DriveScopes.DRIVE_METADATA_READONLY);
private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
public void NotesMain() {
try {
Session session = getSession();
AgentContext agentContext = session.getAgentContext();
this.main();
// (Your code goes here)
} catch(Exception e) {
e.printStackTrace();
}
}
/**
* Creates an authorized Credential object.
* #param HTTP_TRANSPORT The network HTTP Transport.
* #return An authorized Credential object.
* #throws IOException If the credentials.json file cannot be found.
*/
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
// Load client secrets.
InputStream in = JavaAgent.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
if (in == null) {
throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
}
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
public static void main() throws IOException, GeneralSecurityException {
// Build a new authorized API client service.
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME)
.build();
// Print the names and IDs for up to 10 files.
FileList result = service.files().list()
.setPageSize(10)
.setFields("nextPageToken, files(id, name)")
.execute();
List<File> files = result.getFiles();
if (files == null || files.isEmpty()) {
System.out.println("No files found.");
} else {
System.out.println("Files:");
for (File file : files) {
System.out.printf("%s (%s)\n", file.getName(), file.getId());
}
}
}
}
This is the error Ive'd got from the java debug console.
java.io.IOException: Access is denied.
at java.io.File.createNewFile(File.java:894)
at com.google.api.client.util.store.FileDataStoreFactory$FileDataStore.(FileDataStoreFactory.java:96)
at com.google.api.client.util.store.FileDataStoreFactory.createDataStore(FileDataStoreFactory.java:73)
at com.google.api.client.util.store.AbstractDataStoreFactory.getDataStore(AbstractDataStoreFactory.java:55)
at com.google.api.client.auth.oauth2.StoredCredential.getDefaultDataStore(StoredCredential.java:171)
at com.google.api.client.auth.oauth2.AuthorizationCodeFlow$Builder.setDataStoreFactory(AuthorizationCodeFlow.java:744)
at com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow$Builder.setDataStoreFactory(GoogleAuthorizationCodeFlow.java:209)
at JavaAgent.getCredentials(Unknown Source)
at JavaAgent.main(Unknown Source)
at JavaAgent.NotesMain(Unknown Source)
at lotus.domino.AgentBase.runNotes(Unknown Source)
at lotus.domino.NotesThread.run(Unknown Source)

Lotus Notes Integration to Google Team-drive

I have a requirement to create a Lotus Notes java agent that needs to upload a folder/files from local directory to Google Team Drive for scheduled backup. I did some research about the Google API's (https://developers.google.com/api-client-library/java/) for java but I'm having some difficulties trying to understand all those java code as I only have a basic knowledge in java. If I understand it correctly, the api requires a maven repository and need to define all the dependencies which are not supported in Lotus Notes (not sure about this and am I reading the correct documentation).
May be someone can tell me if this is possible and point me out where to start. You might have some sample code that I can use as a reference. Any help and suggestion is very much appreciated.
Thank you.
You might take a look at the Drive Java Quickstart [1], where you will find the prerequisites and links of how to install Gradle (which is pretty similar to Maven) and the steps to build the JAVA application to make the requests to the Drive API.
Apparently, you wouldn’t have a problem to install gradle in lotus notes, either using this plugin [2] or installing eclipse [3], and then installing gradle inside eclipse.
Following the quickstart, the Java Drive documentation [4] and this google guide to upload files [5], I created and tested this code successfully:
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.client.http.FileContent;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;
public class DriveQuickstart {
//General Variables
private static final String APPLICATION_NAME = "Google Calendar API Java Quickstart";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final String TOKENS_DIRECTORY_PATH = "tokens";
/**
* Global instance of the scopes required by this quickstart.
* If modifying these scopes, delete your previously saved tokens/ folder.
*/
private static final List<String> SCOPES = Arrays.asList(DriveScopes.DRIVE);
private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
/**
* Creates an authorized Credential object.
* #param HTTP_TRANSPORT The network HTTP Transport.
* #return An authorized Credential object.
* #throws IOException If the credentials.json file cannot be found.
*/
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
// Load client secrets.
InputStream in = DriveQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
if (in == null) {
throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
public static void main(String... args) throws IOException, GeneralSecurityException {
// Build the news authorized API client services.
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
Drive driveService = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME)
.build();
File fileMetadata = new File();
fileMetadata.setName("Filename");
java.io.File filePath = new java.io.File(“Complete-File-Path”);
FileContent mediaContent = new FileContent("image/jpeg", filePath);
File file = driveService.files().create(fileMetadata, mediaContent)
.setFields("id")
.execute();
System.out.println("File ID: " + file.getId());
}
}
Just for your information, there’s a tool you can use to migrate all your information from Lotus Notes to G suite [6].
[1] https://developers.google.com/drive/api/v3/quickstart/java
[2] https://www.ibm.com/support/knowledgecenter/en/SSYJJF_1.0.0/ApplicationSecurityonCloud/src_irx_gen_gradle.html
[3] https://www.ibm.com/developerworks/lotus/library/notes-eclipse/
[4] https://developers.google.com/resources/api-libraries/documentation/drive/v3/java/latest/
[5] https://developers.google.com/drive/api/v3/manage-uploads
[6] https://support.google.com/a/answer/161642?hl=en

Google Drive 403 Forbidden error

there are already a few people that have asked questions in regards to this, but I still wasn't able to solve my problem.
So, I did the gradle/java quickstart to Print the names and IDs for up to 10 files in my Googledrive. That was fine, but I want to write a java script to upload files on my drive, I inserted the main function below in my java file.
public class DriveCommandLine {
/** Application name. */
private static final String APPLICATION_NAME =
"Drive API Java Quickstart";
/** Directory to store user credentials for this application. */
private static final java.io.File DATA_STORE_DIR = new java.io.File(
System.getProperty("user.home"), ".credentials/drive-java-quickstart");
/** Global instance of the {#link FileDataStoreFactory}. */
private static FileDataStoreFactory DATA_STORE_FACTORY;
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY =
JacksonFactory.getDefaultInstance();
/** Global instance of the HTTP transport. */
private static HttpTransport HTTP_TRANSPORT;
/** Global instance of the scopes required by this quickstart.
*
* If modifying these scopes, delete your previously saved credentials
* at ~/.credentials/drive-java-quickstart
*/
private static final List<String> SCOPES =
Arrays.asList(DriveScopes.DRIVE_METADATA_READONLY);
static {
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
}
/**
* Creates an authorized Credential object.
* #return an authorized Credential object.
* #throws IOException
*/
public static Credential authorize() throws IOException {
// Load client secrets.
InputStream in =
DriveCommandLine.class.getResourceAsStream("/client_secret.json");
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(DATA_STORE_FACTORY)
.setAccessType("offline")
.build();
Credential credential = new AuthorizationCodeInstalledApp(
flow, new LocalServerReceiver()).authorize("user");
System.out.println(
"Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
return credential;
}
/**
* Build and return an authorized Drive client service.
* #return an authorized Drive client service
* #throws IOException
*/
public static Drive getDriveService() throws IOException {
Credential credential = authorize();
return new Drive.Builder(
HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
}
public static void main(String[] args) throws IOException{
//Insert a file
Drive service = getDriveService();
File body = new File();
body.setDescription("A test document");
body.setMimeType("text/plain");
java.io.File fileContent = new java.io.File("D:\\MyFiles\\nkonstantinidis\\Study\\IntelliJ_Shortcuts.txt");
FileContent mediaContent = new FileContent("text/plain", fileContent);
File file = service.files().insert(body, mediaContent).execute();
System.out.println("file ID: " + file.getId());
}
}
And I'm getting an error message shown below when I run it
Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"message" : "Insufficient Permission",
"reason" : "insufficientPermissions"
} ],
"message" : "Insufficient Permission"
}
at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:146)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:432)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
at DriveCommandLine.main(DriveCommandLine.java:114)
I have created the OAuth client ID and enabled google drive but this still doing it's thing.
Could you maybe help me, or even better direct to tutorial for uploading files on google drive, I'm quite bad in Java so bear with me.
Thanks in advance.
You must change SCOPE used for connection (Insufficient Permission message) into appropriate one
private static final List<String> SCOPES = Arrays.asList(DriveScopes.DRIVE_METADATA_READONLY);
From DriveScope.class:
/** View and manage the files in your Google Drive. */
public static final String DRIVE = "https://www.googleapis.com/auth/drive";
/** View and manage its own configuration data in your Google Drive. */
public static final String DRIVE_APPDATA = "https://www.googleapis.com/auth/drive.appdata";
/** View and manage Google Drive files and folders that you have opened or created with this app. */
public static final String DRIVE_FILE = "https://www.googleapis.com/auth/drive.file";
/** View and manage metadata of files in your Google Drive. */
public static final String DRIVE_METADATA = "https://www.googleapis.com/auth/drive.metadata";
/** View metadata for files in your Google Drive. */
public static final String DRIVE_METADATA_READONLY = "https://www.googleapis.com/auth/drive.metadata.readonly";
/** View the photos, videos and albums in your Google Photos. */
public static final String DRIVE_PHOTOS_READONLY = "https://www.googleapis.com/auth/drive.photos.readonly";
/** View the files in your Google Drive. */
public static final String DRIVE_READONLY = "https://www.googleapis.com/auth/drive.readonly";
/** Modify your Google Apps Script scripts' behavior. */
public static final String DRIVE_SCRIPTS = "https://www.googleapis.com/auth/drive.scripts";
Remember to delete saved credentials (created by application) after changing SCOPE

403 Forbidden Error While accessing Google MapsAPI

I am trying to establish connectivity with google maps api using service account. I have a project in place in google maps api, and I have the relvant clientID, .p12 key, email address. I am using google libraries to get the credentials and to call the API as below.
CODE:
package mapsengine;import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.mapsengine.MapsEngine;
import com.google.api.services.mapsengine.model.Map;
import com.google.api.services.mapsengine.model.Layer;
import java.io.File;import java.io.IOException;
import java.util.Collections;
public class Main { /** Provide the ID of the map you wish to read. */
private static final String MAP_ID = "my map id i gave";
private static final String APPLICATION_NAME = "Google-MapsEngineApiSample/1.0";
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
private static final String SERVICE_ACCOUNT_EMAIL= "asajdsjdheemqe#developer.gserviceaccount.com";
private static Credential authorize() throws Exception {
GoogleCredential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT
) .setJsonFactory(JSON_FACTORY)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(Collections.singleton("https://www.googleapis.com/auth/mapsengine"))
.setServiceAccountPrivateKeyFromP12File(new File("key.p12"))
.build();
credential.refreshToken();
System.out.println(credential);
return credential;
}
public static void main(String[] args)
{ try { // Authorize this application to access the user's data.
Credential credential = authorize();
// Create an authorized Maps Engine client with the credential.
MapsEngine mapsEngine = new MapsEngine.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential) .
setApplicationName(APPLICATION_NAME).build();
System.out.println(mapsEngine);
// Make a request to get the details of a particular map.
// Map map = mapsEngine.maps().get(MAP_ID).execute();
System.out.println(map.getName());
System.out.println(map.getDescription());
}
catch (IOException e) {
System.out.println(e.getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
}
}`
I am getting an error as 403 Forbidden
{
"code" : 403,
"errors" : [ {
"domain" : "mapsengine",
"location" : "id",
"locationType" : "parameter",
"message" : "Permission denied (reader access required).",
"reason" : "noReaderAccess"
} ],
"message" : "Permission denied (reader access required)."
}
But I am able to see that the service email account which I am using has edit access, also i tried by giving view access. What else I am missign here. Please help.
you need to go your map, and add your SERVICE_ACCOUNT_EMAIL address and give it can edit or view premission follow this: https://support.google.com/mapsengine/answer/4618526?hl=en

Anyone able to get directory listing feature work in Android

It seems that, recent released Google Drive SDK supports directory listing.
https://developers.google.com/drive/v2/reference/files/list
I try to integrate it into my Android app.
package com.jstock.cloud;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.util.Log;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.services.GoogleKeyInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.extensions.android2.AndroidHttp;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.Drive.Files;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
import com.jstock.gui.Utils;
public class CloudFile {
public final java.io.File file;
public final long checksum;
public final long date;
public final int version;
private CloudFile(java.io.File file, long checksum, long date, int version) {
this.file = file;
this.checksum = checksum;
this.date = date;
this.version = version;
}
public static CloudFile newInstance(java.io.File file, long checksum, long date, int version) {
return new CloudFile(file, checksum, date, version);
}
public static CloudFile loadFromGoogleDrive(String authToken) {
final HttpTransport transport = AndroidHttp.newCompatibleTransport();
final JsonFactory jsonFactory = new GsonFactory();
GoogleCredential credential = new GoogleCredential();
credential.setAccessToken(authToken);
Drive service = new Drive.Builder(transport, jsonFactory, credential)
.setApplicationName(Utils.getApplicationName())
.setJsonHttpRequestInitializer(new GoogleKeyInitializer(ClientCredentials.KEY))
.build();
List<File> files = retrieveAllFiles(service);
Log.i("CHEOK", "size is " + files.size());
for (File file : files) {
Log.i(TAG, "title = " + file.getTitle());
}
return null;
}
/**
* Retrieve a list of File resources.
*
* #param service Drive API service instance.
* #return List of File resources.
*/
private static List<File> retrieveAllFiles(Drive service) {
List<File> result = new ArrayList<File>();
Files.List request = null;
try {
request = service.files().list();
} catch (IOException e) {
Log.e(TAG, "", e);
return result;
}
do {
try {
FileList files = request.execute();
result.addAll(files.getItems());
request.setPageToken(files.getNextPageToken());
} catch (IOException e) {
Log.e(TAG, "", e);
request.setPageToken(null);
}
} while (request.getPageToken() != null && request.getPageToken().length() > 0);
Log.i("CHEOK", "yup!");
return result;
}
private static final String TAG = "CloudFile";
}
I always get 0 file returned from server, and there isn't any exception being thrown. Is there anything I had missed out?
You have to request access to the full Drive scope to list all files: https://developers.google.com/drive/scopes#requesting_full_drive_scope_for_an_app
If you use the default (and recommended) scope https://www.googleapis.com/auth/drive.file, you will only be able to see files created or opened by the app.