modifiedDate and lastViewedByMeDate query not woring in Drive API Java - java

I have a query that modifiedDate = '2013-09-01T12:00:00' and lastViewedByMeDate = '2013-09-01T12:00:00' those type of queries are not working and throws error as:
com.google.api.client.googleapis.json.GoogleJsonResponseException:
500 Internal Server Error
{
"code" : 500,
"errors" : [ {
"domain" : "global",
"message" : "Internal Error",
"reason" : "internalError"
} ],
"message" : "Internal Error"
}
My Code is
String searchQuery="lastViewedByMeDate = '2013-09-01T12:00:00'";
// String searchQuery="modifiedDate = '2013-09-01T12:00:00'";
Files.List request = this.driveService.files().list();
request.setQ(searchQuery);
FileList files = request.execute();
for (File file : files.getItems()) {
// ...........
}
There is no error in code since this type of queries are not running.

Looks like a bug.
Using https://developers.google.com/drive/v2/reference/files/list#try-it, your query throws a 500, but changing the comparison operator from '=' to '>=' works OK.
It is a bit unusual to query for a precise date and time anyway (remember that timestamps are often updated asynchronously in Google Drive). So it maybe that you can use a date range to meet your needs.
It may well be that the bug is simply in the documentation, and that '=' is not actually supported.

Related

Google drive V3 java api syntax for searching files

My Question is - How to pass the search parameters to the method. There is no any documentation or sample I found for search.Any sample example will work for me.
Source Code
String npTok = null;
String queryParam ="modifiedTime > '2012-06-04T12:00:00' and (mimeType
contains 'image/' )";
com.google.api.services.drive.Drive.Files.List qry = drive.files().list().setFields("files(id, name)").setQ(queryParam);
com.google.api.services.drive.model.FileList gLst = qry.execute();
for (com.google.api.services.drive.model.File gFl : gLst.getItems())
{
String id = gFl.getId();
System.out.println("ID==>"+id);
}
Error
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"location" : "fields",
"locationType" : "parameter",
"message" : "Invalid field selection name",
"reason" : "invalidParameter"
} ],
"message" : "Invalid field selection name"
}
Thanks all
The error message is objecting to the fields parameter, not the q. Your syntax is correct for v3, so I suspect your client library is still using v2. Try replacing files(id,name) with items(id,title). If that works, you're using an old version of the library.
refer bellow link, you can get sample code and more information about Google drive V3 java api searching.
https://developers.google.com/drive/v3/web/search-parameters
https://developers.google.com/drive/v3/reference/files/list
https://developers.google.com/drive/v3/web/quickstart/java

Groovy/Java Google storage auth and request

Is there any simple code example for Groovy/Java to authenticate and make request to Google Storage. I want to use this API to copy objects from one bucket to another:
https://cloud.google.com/storage/docs/json_api/v1/objects/copy
Here is what I tried:
String sourceStorageID = "XXX"
String destinationStorageID = "YYY"
String sourceFileName = "fileXXX"
String destinationFileName = "fileYYY"
//https://www.googleapis.com/storage/v1/b/sourceBucket/o/sourceObject/copyTo/b/destinationBucket/o/destinationObject
String urlToCopyFile = "https://www.googleapis.com/storage/v1/b/" + sourceStorageID + "/o/" + sourceFileName + "/copyTo/b/" + destinationStorageID + "/o/" + destinationFileName
RestBuilder rest = new RestBuilder()
def exportFinishedJSON = rest.get(objectsListURL) {}?.json
I am getting this response:
{"error":{"message":"Anonymous users does not have storage.objects.list access to bucket XXX.","errors":[{"message":"Anonymous users does not have storage.objects.list access to bucket XXX","location":"Authorization","reason":"required","locationType":"header","domain":"global"}],"code":401}}
I know I need to make authentication first, but how ? I read tons and tons of documentation but there isn't any simple example for Java to implement. It's really messy and bloated with so many informations and I am tired of reading and searching it.
I also searched solution with ApiKey and in documentation it says just to append it as param to URL, I tried it like this:
String urlToCopyFile = "https://www.googleapis.com/storage/v1/b/" + sourceStorageID + "/o/" + sourceFileName + "/copyTo/b/" + destinationStorageID + "/o/" + destinationFileName + "&key=" + myApiKey
but no success.
Is there any good simple example of solution for my problem ?
Thanks in advance
EDIT: Also tried with different approach like this:
if (storageObject == null) {instance.authenticate();}
StorageObject newObject = new StorageObject()
newObject.setName(destinationObjectName)
Storage.Objects.Copy request = storageObject.objects().copy(sourceStorageID, sourceObjectName, destinationStorageID, destinationObjectName, newObject);
request.execute();
now getting this error:
GoogleJsonResponseException occurred when processing request: [GET] /concierge/test/index
400 Bad Request
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"message" : "Required",
"reason" : "required"
} ],
"message" : "Required"
}. Stacktrace follows:
com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"message" : "Required",
"reason" : "required"
} ],
"message" : "Required"
}

Create sheet and update data with one request

I want to implement Google sheets api request with one api call.
I managed to implement this code:
List<Request> requests = new ArrayList<>();
List<CellData> values = new ArrayList<>();
values.add(new CellData()
.setUserEnteredValue(new ExtendedValue()
.setStringValue("Hello World!")));
requests.add(new Request().setAddSheet(new AddSheetRequest()
.setProperties(new SheetProperties()
.setTitle("scstc")))
.setUpdateCells(new UpdateCellsRequest()
.setStart(new GridCoordinate()
.setSheetId(0)
.setRowIndex(0)
.setColumnIndex(0))
.setRows(Arrays.asList(
new RowData().setValues(values)))
.setFields("userEnteredValue,userEnteredFormat.backgroundColor"))
);
BatchUpdateSpreadsheetRequest body = new BatchUpdateSpreadsheetRequest().setRequests(requests);
BatchUpdateSpreadsheetResponse response = service.spreadsheets().batchUpdate(spreadsheetId, body).execute();
But I get error:
400 Bad Request
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"message" : "Invalid value at 'requests[0]' (oneof), oneof field 'kind' is already set. Cannot set 'updateCells'",
"reason" : "badRequest"
} ],
"message" : "Invalid value at 'requests[0]' (oneof), oneof field 'kind' is already set. Cannot set 'updateCells'",
"status" : "INVALID_ARGUMENT"
}
at com.google.sheet.impl.GoogleSheetBasicTest1_____1.hello(GoogleSheetBasicTest1_____1.java:133)
Do you how how I can fix this issue?
Each Request object is intended to have just a single value set within it. You are setting two values:
requests.add(new Request()
.setAddSheet(...)
.setUpdateCells(...));
Instead of doing the above, you need to use two request objects:
requests.add(new Request().setAddSheet(...));
requests.add(new Request().setUpdateCells(...));
#Sam is correct, however if you are using the JSON representation make sure that your formatting is set correctly in the dictionaries you are making. I found the following formating helpfull, found in the Google Devs' Formatting cells with the Google Sheets API
blogpost:
reqs = {'requests': [
# frozen row 1, request #1
{'updateSheetProperties': {
'properties': {'gridProperties': {'frozenRowCount': 1}},
'fields': 'gridProperties.frozenRowCount',
}},
# embolden row 1, request #2
{'repeatCell': {
'range': {'endRowIndex': 1},
'cell': {'userEnteredFormat': {'textFormat': {'bold': True}}},
'fields': 'userEnteredFormat.textFormat.bold',
}},
]}
*I am new to adding information to this site. Sorry if this is not he best way to add the information but I just want to help out. I had this problem while using python instead of java and found that it was a simple error of were the brackets where.

Insert object (as a folder) in Google Cloud Storage using JSON API with Java

I already know that there is no folders inside a Google Cloud Storage (they are treated as objects), so please have a look of my question and you can understand what i mean. Thanks :-)
This is my method to upload an object, and in my specific case, i would like to upload a "folder", so a file that end with a '/' (for example: 'newfolder/'), but i receive a GoogleJson error in the execute() at the end of my code.
[Error]:
Uncaught exception from servlet
com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 OK
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"message" : "Required",
"reason" : "required"
}, {
"domain" : "global",
"message" : "Required",
"reason" : "required"
}, {
"domain" : "global",
"message" : "Required",
"reason" : "required"
} ],
"message" : "Required"
}
[my code inside the method]:
StorageObject objectMetadata = null;
//default bucket
String bucketRootName = “defaultbucketname”;
//First Folder
String folderAppName = “myfolder”;
//folder that i want to create (upload)
folderName+="/";
String folderPath = folderAppName + "/" + folderName;
if (useCustomMetadata) {
List<ObjectAccessControl> acl = Lists.newArrayList();
acl.add( new ObjectAccessControl().setEntity("allAuthenticatedUsers").setRole("OWNER"));
objectMetadata = new StorageObject()
.setName(folderPath)
.setAcl(acl)
.setContentDisposition("attachment");
}
Storage.Objects.Insert insertObject = storage.objects().insert(bucketRootName, objectMetadata);
StorageObject metadata = insertObject.execute();
return metadata;
In order to have a bucket with a path like this:
defaultbucketname/myfolder/folderName/
Does anyone know how to solve it?
Thank you so much
Uploaded objects must have a Content-Type, even if they're zero bytes large.
Also, I'm pretty sure that you must upload an actual file, even if it is zero bytes in size.
I dont think you can create a folder that way. But you can create it while uploading the file by setting the name.
e.g. if you want create a file under foldA/foldB/test.txt, you can do it following way.
InputStream is = Files.newInputStream(path); //path if java.nio.file.Path
String mimeType = Files.probeContentType(path);
InputStreamContent isContent = new InputStreamContent(mimeType, is);
StorageObject objectMetadata = new StorageObject();
Storage.Objects.Insert insertObject = storage.objects().insert(bucketRootName, objectMetadata,isContent);
insertObject.setName("foldA/foldB/"+path.getFileName().toString()); // path.getFileName().toString() will give u test.txt
insertObject.execute();

google drive java api error 400 when changing file owner

Im trying to change file owner, from writer to owner but I'm still getting:
com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"message" : "Bad Request",
"reason" : "badRequest"
} ],
"message" : "Bad Request"
}
And here's some part of source code:
//getting writer permission
Permission permission = service.permissions().get(fileId, permToChange.get(j)).execute();
permission.setRole("owner");
service.permissions().update(fileId, permToChange.get(j), permission).setTransferOwnership(true).execute();
Both accounts current owner and new owner has same domain.
I was trying delete writer account, add new one and change ownership too but always got same result.

Categories