Reputation: 31
I'm working on some improvement on our google drive integration.
Current state:
There is already implementation of saving files into Google Drive folders using hard-coded folderId. This works with no problems.
Now: I want to extend this logic and I need for this list of all folders.
So I followed this guide:
https://developers.google.com/drive/api/guides/search-files
And the problem is that I receive only **one** folder but in google drive there is 10.
Can anyone has any idea what I missed or overlooked? Why result doesn't contain nextPageToken? Spent whole day on it and this drives me crazy.
This is my method (i'm using service account for connection):
@Override
public List<File> getAllFolders() throws IOException {
Drive service = googleDriveProvider.getService();
List<File> files = new ArrayList<>();
String pageToken = null;
do {
FileList result = service.files().list()
.setQ("mimeType='application/vnd.google-apps.folder'")
.setSpaces("drive")
.setSupportsAllDrives(true)
.setIncludeItemsFromAllDrives(true)
.setFields("nextPageToken, files(id, name, parents)")
.setPageToken(pageToken)
.execute();
for (File file : result.getFiles()) {
System.out.printf("Found file: %s (%s)\n",
file.getName(), file.getId());
}
files.addAll(result.getFiles());
pageToken = result.getNextPageToken();
} while (pageToken != null);
return files;
}
And this is GoogleDriveProvider:
@Service
public class GoogleDriveProvider {
private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
private static final Set<String> SCOPES = DriveScopes.all();
private static final String GET_DRIVE_SERVICE_ERROR_MESSAGE = "Getting instance of Google drive has failed, error: [%s]";
@Value("${google.drive.service.account.auth.json}")
private String authJson;
@Value("${info.app.name}")
private String appName;
public Drive getService() throws GoogleDriveException {
try {
final NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredentials credentials = GoogleCredentials.fromStream(
new ByteArrayInputStream(authJson.getBytes())).createScoped(SCOPES);
credentials.refreshIfExpired();
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);
return new Drive.Builder(httpTransport, JSON_FACTORY, requestInitializer)
.setApplicationName(appName)
.build();
} catch (IOException | GeneralSecurityException e) {
throw new GoogleDriveException(
format(GET_DRIVE_SERVICE_ERROR_MESSAGE, e.getMessage()), e);
}
}
}
Upvotes: 1
Views: 486
Reputation: 31
Problem solved. Folders must be created by the service account or must be shared with service account first.
Upvotes: 2