I want to list all files into my Google Drive account. I tried to use this code:
@Test
public void hello() throws Exception
{
Drive service = getDriveService();
retrieveAllFiles(service);
}
private static final String SERVICE_ACCOUNT_EMAIL = "test@sonora-project.iam.gserviceaccount.com";
private static final String userEmail = "test@gmail.com";
public Drive getDriveService() throws GeneralSecurityException,
IOException
{
ClassLoader classLoader = this.getClass().getClassLoader();
java.io.File path = new java.io.File(classLoader.getResource("test-test123.p12").getFile());
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(Arrays.asList(DriveScopes.DRIVE, DriveScopes.DRIVE_FILE, DriveScopes.DRIVE_METADATA))
.setServiceAccountUser(userEmail)
.setServiceAccountPrivateKeyFromP12File(path)
.build();
Drive service = new Drive.Builder(httpTransport, jsonFactory, null)
.setApplicationName("sonora project")
.setHttpRequestInitializer(credential).build();
return service;
}
private static List<File> retrieveAllFiles(Drive service) throws IOException
{
List<File> result = new ArrayList<File>();
Drive.Files.List request = service.files().list();
do
{
try
{
FileList files = request.execute();
result.addAll(files.getFiles());
request.setPageToken(files.getNextPageToken());
}
catch (IOException e)
{
System.out.println("An error occurred: " + e);
request.setPageToken(null);
}
}
while (request.getPageToken() != null
&& request.getPageToken().length() > 0);
return result;
}
I get error 401 when I try to list the files. Do you know how I can fix this?
When I run only the authentication part the code is working.