403 Forbidden Error While accessing Google MapsAPI - google-maps

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

Related

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

Getting domain installs for my Google Docs Add-on

We have a Google-docs Add-on (built on Google Apps Script) for which we enabled the Google Apps Marketplace SDK - so that Google Apps Administrators could install our add-on at the domain level.
We have noticed a few domains have now installed our add-on - but I can't seem to find a way to get information on which domains have installed us. Is it even possible?
I have tried the Marketplace license API https://developers.google.com/apps-marketplace/v2/reference/ but it fails with a 403 error - Not authorized to access the application ID.
{
"error": {
"errors": [
{
"domain": "global",
"reason": "forbidden",
"message": "Not authorized to access the application ID"
}
],
"code": 403,
"message": "Not authorized to access the application ID"
}
}
I even tried by creating a service account and accessed the API using the service account but got the same error.
Any input would be awesome.
Here's my Java (Groovy technically) code so far (the response is the json I've pasted above):
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport
import com.google.api.client.http.GenericUrl
import com.google.api.client.http.HttpRequest
import com.google.api.client.http.HttpRequestFactory
import com.google.api.client.http.HttpTransport
import com.google.api.client.json.JsonFactory
import com.google.api.client.json.jackson2.JacksonFactory
import org.springframework.security.access.annotation.Secured
class DataController {
/**
* Be sure to specify the name of your application. If the application name is {#code null} or
* blank, the application will log a warning. Suggested format is "MyCompany-ProductName/1.0".
*/
private static final String APPLICATION_NAME = "My app name";
private static final String APPLICATION_ID = "12 digit project number";
/** E-mail address of the service account. */
private static final String SERVICE_ACCOUNT_EMAIL = "12digitproejectnumber-compute#developer.gserviceaccount.com";
/** Global instance of the HTTP transport. */
private static HttpTransport httpTransport;
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
def getLicensedInfo() {
try {
try {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(Collections.singleton("https://www.googleapis.com/auth/appsmarketplace.license"))
.setServiceAccountPrivateKeyFromP12File(new File("a/valid/path/to/key.p12"))
.build();
credential.refreshToken();
String token = credential.getAccessToken();
HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
GenericUrl url = new GenericUrl("https://www.googleapis.com/appsmarket/v2/licenseNotification/"+APPLICATION_ID);
HttpRequest request = requestFactory.buildGetRequest(url);
com.google.api.client.http.HttpResponse response = request.execute();
log.debug(response.parseAsString());
return;
} catch (IOException e) {
System.err.println(e.getMessage());
}
} catch (Throwable t) {
t.printStackTrace();
}
}
}
When making the request to the GAM License API you need to use the same Google Developers Console project that you used for your listing. In the case of an add-on, this is the console project associated with the script.

401 response when athenticating via Service Account and OAuth2 to GoogleDrive

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.

Refresh token and reuse this token to get new access token java

How do I get the refresh token and the access token from the first time authorization code? And, how do I reuse this refresh token to get a new access token to upload to Google Drive using the Java API? This is not a web application. It's in Java Swing code.
We can reuse the refresh token to get new access token by following code
public class OAuthRefreshToken implements CredentialRefreshListener {
public static GoogleCredential getAccessTokenFromRefreshToken( String refreshToken, HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory, String CLIENT_ID, String CLIENT_SECRET) throws IOException
{
GoogleCredential.Builder credentialBuilder = new GoogleCredential.Builder()
.setTransport(transport).setJsonFactory(jsonFactory)
.setClientSecrets(CLIENT_ID, CLIENT_SECRET);
credentialBuilder.addRefreshListener(new OAuthRefreshToken());
GoogleCredential credential = credentialBuilder.build();
credential.setRefreshToken(refreshToken);
credential.refreshToken();
return credential;
}
#Override
public void onTokenErrorResponse(Credential arg0, TokenErrorResponse arg1)
throws IOException {
// TODO Auto-generated method stub
System.out.println("Error occured !");
System.out.println(arg1.getError());
}
#Override
public void onTokenResponse(Credential arg0, TokenResponse arg1)
throws IOException {
// TODO Auto-generated method stub
System.out.println(arg0.getAccessToken());
System.out.println(arg0.getRefreshToken());
}
}
Here is a solution I recently made up from the basic example in the Google Drive docs and some experimenting:
The IApiKey contains the static strings CLIENT_ID, and so on. ITokenPersistence is an interface which allows to load and save a token (as String). It decouples the persistence mechanism (I used Preferences for an Eclipse e4 RCP application) from the Uploader. This can be as simple as storing the token in a file The IAthorizationManager is an interface which is is used to let the user grant acces and enter the code to create the refresh token. I implemented a Dialog containing a browser widget to grant access and a text box to copy and paste the code to. The custom exception GoogleDriveException hides the API classes from the rest of the code.
public final class Uploader implements IApiKey {
public static final String TEXT_PLAIN = "text/plain";
private final ITokenPersistence tokenManager;
private final IAuthorizationManager auth;
public Uploader(final ITokenPersistence tm, final IAuthorizationManager am) {
this.tokenManager = tm;
this.auth = am;
}
private GoogleCredential createCredentialWithRefreshToken(
final HttpTransport transport,
final JsonFactory jsonFactory,
final String clientId,
final String clientSecret,
final TokenResponse tokenResponse) {
return new GoogleCredential.Builder().setTransport(transport)
.setJsonFactory(jsonFactory)
.setClientSecrets(clientId, clientSecret)
.build()
.setFromTokenResponse(tokenResponse);
}
/**
* Upload the given file to Google Drive.
* <P>
* The name in Google Drive will be the same as the file name.
* #param fileContent a file of type text/plain
* #param description a description for the file in Google Drive
* #return Answer the ID of the uploaded file in Google Drive.
* Answer <code>null</code> if the upload failed.
* #throws IOException
* #throws {#link GoogleDriveException} when a <code>TokenResponseException</code> had been
* intercepted while inserting (uploading) the file.
*/
public String upload(final java.io.File fileContent, final String description) throws IOException, GoogleDriveException {
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
// If we do not already have a refresh token a flow is created to get a refresh token.
// To get the token the user has to visit a web site and enter the code afterwards
// The refresh token is saved and may be reused.
final GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport,
jsonFactory,
CLIENT_ID,
CLIENT_SECRET,
Arrays.asList(DriveScopes.DRIVE))
.setAccessType("offline")
.setApprovalPrompt("auto").build();
final String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
final String refreshToken = this.tokenManager.loadRefreshToken();
GoogleCredential credential = null;
if( refreshToken == null ) {
// no token available: get one
String code = this.auth.authorize(url);
GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
this.tokenManager.saveRefreshToken(response.getRefreshToken());
credential = this.createCredentialWithRefreshToken(httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, response);
}
else {
// we have a token, if it is expired or revoked by the user the service call (see below) may fail
credential = new GoogleCredential.Builder()
.setJsonFactory(jsonFactory)
.setTransport(httpTransport)
.setClientSecrets(CLIENT_ID, CLIENT_SECRET)
.build();
credential.setRefreshToken(refreshToken);
}
//Create a new authorized API client
final Drive service = new Drive.Builder(httpTransport, jsonFactory, credential)
.setApplicationName(APP_NAME)
.build();
//Insert a file
final File body = new File();
body.setTitle(fileContent.getName());
body.setDescription(description);
body.setMimeType(TEXT_PLAIN);
final FileContent mediaContent = new FileContent(TEXT_PLAIN, fileContent);
try {
final File file = service.files().insert(body, mediaContent).execute();
return ( file != null ) ? file.getId() : null;
} catch (TokenResponseException e) {
e.printStackTrace();
throw new GoogleDriveException(e.getDetails().getErrorDescription(), e.getCause());
}
}
}

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.