OAuth2 and Drive API, can't list/retrieve files - java

I have a web application that needs to list all files from my Google Drive and then fetch them when clicked.
I use OAuth for authenticating and it seems to work (the same code works well with Calendar API). I tried different scopes in serviceAccountScopes with no avail.
Basically authentication is:
credential = new GoogleCredential.Builder().
setTransport(HTTP_TRANSPORT).
setJsonFactory(JSON_FACTORY).
setServiceAccountId(apiEmail).
setServiceAccountScopes(DriveScopes.DRIVE).
setServiceAccountPrivateKeyFromP12File(p12File).build();
credential.refreshToken();
service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).
setApplicationName("My API").build();
edit: I should Add that credential's accessToken is null before refreshToken() call.
After that I try:
FileList files = service.files().list().execute();
The returned FileList is (should contain items):
{"etag":"\"_U9FTLXcHskmKgrWAZqJlfW8kCo/vyGp6PvFo4RvsFtPoIWeCReyIC8\"","items":[],"kind":"drive#fileList","selfLink":"https://www.googleapis.com/drive/v2/files"}
If I check that selfLink the contents is:
{
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "dailyLimitExceededUnreg",
"message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.",
"extendedHelp": "https://code.google.com/apis/console"
}
],
"code": 403,
"message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
}
}
Daily limit is not an issue here. (I guess this has nothing to do with this issue, since: https://stackoverflow.com/a/10639679/2090125). Also, I have enabled Drive and Drive SDK in Console (https://stackoverflow.com/a/10329353/2090125).
When downloading a file this is performed:
File file = service.files().get(fileId).execute();
And it produces this (fileId exists):
An error occured: com.google.api.client.googleapis.json.GoogleJsonResponseException: 404 Not Found
{
"code" : 404,
"errors" : [ {
"domain" : "global",
"message" : "File not found: 0B97KF40kTwrTaTllMnZCTV9ZSnM",
"reason" : "notFound"
} ],
"message" : "File not found: 0B97KF40kTwrTaTllMnZCTV9ZSnM"
}
And again when checking https://www.googleapis.com/drive/v2/files/0B97KF40kTwrTaTllMnZCTV9ZSnM the same "dailyLimitExceededUnreg" is seen.
What is going on here, is there a problem in my authentication? Should I configure Drive Integration in Drive SDK somehow? From Googles documentation I have understood that it's not necessary and the methods I'm using should work without further configuring.

Related

Able to access bucket in gcloud and Python API but not Java API

I'm working on a project that is includes a process to store files into Google Cloud Storage.
The initial prototype was in Python and works fine, however when porting the codebase over to Java I am unable to access the bucket.
The Java project is built with Gradle and development is through NetBeans. The ServiceAccount is a keyfile with restricted access, only allowing for read/write behavior from this particular bucket.
// The Java code, which should be enough to grab the bucket.
Storage storage = StorageOptions.getDefaultInstance().getService();
Bucket bucket = storage.get(BUCKET_NAME);
// For comparison, the Python setup.
storage_client = storage.Client()
self.bucket = storage_client.bucket(bucket_name)
When manually running the project from Gradle the result is,
Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException: 403
Forbidden
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"message" : "xxx#xxx.iam.gserviceaccount.com does not have storage.buckets.get access to xxx.",
"reason" : "forbidden"
} ],
"message" : "xxx#xxx.iam.gserviceaccount.com does not have storage.buckets.get access to xxx."
}
Slightly different when running from within NetBeans itself:
Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException: 401
Unauthorized
{
"code" : 401,
"errors" : [ {
"domain" : "global",
"location" : "Authorization",
"locationType" : "header",
"message" : "Anonymous users does not have storage.buckets.get access to a1s-submissions.",
"reason" : "required"
} ],
"message" : "Anonymous users does not have storage.buckets.get access to a1s-submissions."
}
All of these methods are returning the expected results
So I know at least the file is being read.
StorageOptions.getAppEngineAppId());
StorageOptions.getDefaultProjectId());
StorageOptions.CREDENTIAL_ENV_NAME);GOOGLE_APPLICATION_CREDENTIALS
StorageOptions.getDefaultInstance().getApplicationName());
StorageOptions.getDefaultInstance().getProjectId());
StorageOptions.getDefaultInstance().getCredentials()
.getAuthenticationType());
StorageOptions.getLibraryName());
So given that I can access the bucket via gcloud and python, I know the account has authorization, however I cannot seem to uncover the cause for this error.
Oddly, the solution here was in fact to relax the permissions on the service account. I didn't have access to this at the time but was finally able to check this today.
For whatever reason still unknown to me, Python was able to carry out the same operations with the original service account authorization settings while Java required additional rights granted.

using google api explorer to upload data to google cloud storage

i am trying to use google api explorer to first try to insert an object to google cloud storage.
the request looks like
POST https://www.googleapis.com/storage/v1/b/visionapibucket/o?key={YOUR_API_KEY}
{
"contentType": "image/jpeg",
"uploadType": "media",
"path": "/upload/storage/v1/b/visionapibucket/o"
}
but i see the error as
400 HTTP/2.0 400
- Show headers -
{
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Required"
},
{
"domain": "global",
"reason": "wrongUrlForUpload",
"message": "Upload requests must include an uploadType URL parameter and a URL path beginning with /upload/",
"extendedHelp": "https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload"
}
],
"code": 400,
"message": "Required"
}
}
not sure what i am missing. please advise
Looks like a bug on the website. It doesn't seem like the explorer supports media.
The request it generated looks like:
POST https://www.googleapis.com/storage/v1/b/visionapibucket/o?key={YOUR_API_KEY}
But a proper upload request would look like:
POST https://www.googleapis.com/upload/storage/v1/b/visionapibucket/o?key={YOUR_API_KEY}&uploadType=media&name=myfile.jpeg
You'll also want to include a "Content-Type" header specifying that it's a JPEG image.
There's a guide on the various ways to upload objects using the JSON API here. The specific type you're looking for is like a simple upload.

How to find user in google admin sdk

I'd like to find if user with certain username exists on my Gmail. So far I tried:
String query = "email='"+username+"#my.domain.com'";
users = directoryService.users().list().setQuery(query).execute();
But I only get:
13:47:12.654 [1651372403#qtp-1044945601-1] ERROR p.e.u.d.g.a.m.SDKGAManagementServiceImpl(153) - com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"message" : "Bad Request",
"reason" : "badRequest"
} ],
"message" : "Bad Request"
}
I tried to query for a user with known username and I got desired response so I'm certain that the issue lies here. Could someone provide any help?
If you want to find the user using admin sdk, then you should give query like query=email=xxxx#domain.com. Also, even though its not mentioned in documentation, for users.list,you should give domain name too.
After giving the above parameters, I was able to successfully find the user. Let me know if you have questions.

Google Cloud Storage Java API - Deleting a file

How do I set a "WRITER" permission on a GCS bucket?
I am trying to delete a file on cloud storage using:
cloudstorage.objects().delete(bucket, object).execute();
and get the following error:
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"message" : "Forbidden",
"reason" : "forbidden"
} ],
"message" : "Forbidden"
}
With gsutil, like this:
gsutil acl ch -u email#address.com:W gs://bucket-name
Alternately, you can go to the Developer's Console, head over to storage > Cloud Storage > Storage browser, click on the "...", then "edit bucket permissions", then click "+ Add item", choose "user", the email address, and Writer, then click "Save".
Alternately, you can do this programmatically with the JSON API, using the storage.bucketAccessControls.insert method.

Google Drive setWritersCanShare(false) and update of a File in JAVA

I'm trying to put the option "setWritersCanShare" of a file to FALSE. Now I am the owner of the file and I want that the file editors can't share the File. I can get the file and change its permission (via API) without problmes, but when I try to change the "setWritersCanShare" option, I get this response:
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"location" : "Authorization",
"locationType" : "header",
"message" : "The authenticated user does not have the required access to the file 0B0o1ZH_FIoLGUER2UFptYi1CVEU",
"reason" : "userAccess"
} ],
"message" : "The authenticated user does not have the required access to the file 0B0o1ZH_FIoLGUER2UFptYi1CVEU"
}
This is the file update code:
Drive service = new Drive.Builder(httpTransport, jsonFactory, null).setHttpRequestInitializer(credential).setApplicationName("La fiesta").build();
File file = service.files().get(fileID).execute();
file.setWritersCanShare(false);
File fileUpdate=service.files().update(fileID, file).execute();
What it's my error?
Thanks and regards
Try the operation in the Google API Explorer and see if the result is the same.
The error seems to indicate that the authenticated user isn't actually the owner of the file. Are you sure you're authenticating as the file owner (not a Service Account)?

Categories