Create sheet and update data with one request - java

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.

Related

google calendar api delete future events

I am trying to delete future google calendar events, from the docs it tells you to use events.update() and the closest that I have got was with this:
Events events = calendar.events().instances("primary", eventId).execute();
Event instance = events.getItems().get(0);
String[] recurrence = new String[]{"RRULE:UNTIL=" + new DateTime(new Date())};
instance.setRecurrence(Arrays.asList(recurrence));
calendar.events().update("primary", eventId, instance).execute();
and gives me the following:
com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
"code": 400,
"errors": [
{
"domain": "global",
"message": "Value 'k6nni7i7p54hb82p3p6eh9emg8_20180830T174500Z' in content does not agree with value 'k6nni7i7p54hb82p3p6eh9emg8'. This can happen when a value set through a parameter is inconsistent with a value set in the request.",
"reason": "invalidParameter"
}
],
"message": "Value 'k6nni7i7p54hb82p3p6eh9emg8_20180830T174500Z' in content does not agree with value 'k6nni7i7p54hb82p3p6eh9emg8'. This can happen when a value set through a parameter is inconsistent with a value set in the request."
}
Any help would be appreciated, thanks!
Deleting events using Calendar API would make use of the events.delete. You can test this using the Try-it.

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

Cloudera Navigator API fail to fetch nested data

I am working in Cloudera Manager Navigator REST API where extracting result is working fine, but unable to get any nested value.
The type of data is extracting as below.
{
"parentPath": "String",
"customProperties": "Map[string,string]",
"sourceType": "String",
"entityType": "String"
}
And data should be like
{
"parentPath": "abcd",
"customProperties": {
"nameservice" : "xyz"
},
"sourceType": "rcs",
"entityType": "ufo"
}
But I am getting key-value result as follows.
parentPath :abcd
customProperties : null
sourceType : rcs
entityType : ufo
In above response data, "customProperties" is coming with a null value where it should return a map object contains ["nameservice" : "xyz"]. This is the problem with following code snippet.
MetadataResultSet metadataResultSet = extractor.extractMetadata(null, null,"sourceType:HDFS", "identity:*");
Iterator<Map<String, Object>> entitiesIt = metadataResultSet.getEntities().iterator();
while(entitiesIt.hasNext()){
Map<String, Object> result = entitiesIt.next();
for(String data : result.keySet()){
System.out.println(" key:"+data+" value:"+result.get(data));
}
}
Can you suggest me how to get the nested value where datatype is complex.
have u checked how the data looks on navigator ui? You can first verify that once, and also try cloudera /entities/entity-id rest API in browser to check how json response is coming

Update nested field in an index of ElasticSearch with Java API

I am using Java API for CRUD operation on elasticsearch.
I have an typewith a nested field and I want to update this field.
Here is my mapping for the type:
"enduser": {
"properties": {
"location": {
"type": "nested",
"properties":{
"point":{"type":"geo_point"}
}
}
}
}
Of course my enduser type will have other parameters.
Now I want to add this document in my nested field:
"location":{
"name": "London",
"point": "44.5, 5.2"
}
I was searching in documentation on how to update nested document but I couldn't find anything. For example I have in a string the previous JSON obect (let's call this string json). I tried the following code but seems to not working:
params.put("location", json);
client.prepareUpdate(index, ElasticSearchConstants.TYPE_END_USER,id).setScript("ctx._source.location = location").setScriptParams(params).execute().actionGet();
I have got a parsing error from elasticsearch. Anyone knows what I am doing wrong ?
You don't need the script, just update it.
UpdateRequestBuilder br = client.prepareUpdate("index", "enduser", "1");
br.setDoc("{\"location\":{ \"name\": \"london\", \"point\": \"44.5,5.2\" }}".getBytes());
br.execute();
I tried to recreate your situation and i solved it by using an other way the .setScript method.
Your updating request now would looks like :
client.prepareUpdate(index, ElasticSearchConstants.TYPE_END_USER,id).setScript("ctx._source.location =" + json).execute().actionGet()
Hope it will help you.
I am not sure which ES version you were using, but the below solution worked perfectly for me on 2.2.0. I had to store information about named entities for news articles. I guess if you wish to have multiple locations in your case, it would also suit you.
This is the nested object I wanted to update:
"entities" : [
{
"disambiguated" : {
"entitySubTypes" : [],
"disambiguatedName" : "NameX"
},
"frequency" : 1,
"entityType" : "Organization",
"quotations" : ["...", "..."],
"name" : "entityX"
},
{
"disambiguated" : {
"entitySubType" : ["a", "b" ],
"disambiguatedName" : "NameQ"
},
"frequency" : 5,
"entityType" : "secondTypeTest",
"quotations" : [ "...", "..."],
"name" : "entityY"
}
],
and this is the code:
UpdateRequest updateRequest = new UpdateRequest();
updateRequest.index(indexName);
updateRequest.type(mappingName);
updateRequest.id(url); // docID is a url
XContentBuilder jb = XContentFactory.jsonBuilder();
jb.startObject(); // article
jb.startArray("entities"); // multiple entities
for ( /*each namedEntity*/) {
jb.startObject() // entity
.field("name", name)
.field("frequency",n)
.field("entityType", entityType)
.startObject("disambiguated") // disambiguation
.field("disambiguatedName", disambiguatedNameStr)
.field("entitySubTypes", entitySubTypeArray) // multi value field
.endObject() // disambiguation
.field("quotations", quotationsArray) // multi value field
.endObject(); // entity
}
jb.endArray(); // array of nested objects
b.endObject(); // article
updateRequest.doc(jb);
Blblblblblblbl's answer couldn't work for me atm, because scripts are not enabled in our server. I didn't try Bask's answer yet - Alcanzar's gave me a hard time, because I supposedly couldn't formulate the json string correctly that setDoc receives. I was constantly getting errors that either I am using objects instead of fields or vice versa. I also tried wrapping the json string with doc{} as indicated here, but I didn't manage to make it work. As you mentioned it is difficult to understand how to formulate a curl statement at ES's java API.
A simple way to update the arraylist and object value using Java API.
UpdateResponse update = client.prepareUpdate("indexname","type",""+id)
.addScriptParam("param1", arrayvalue)
.addScriptParam("param2", objectvalue)
.setScript("ctx._source.field1=param1;ctx._source.field2=param2").execute()
.actionGet();
arrayvalue-[
{
"text": "stackoverflow",
"datetime": "2010-07-27T05:41:52.763Z",
"obj1": {
"id": 1,
"email": "sa#gmail.com",
"name": "bass"
},
"id": 1,
}
object value -
"obj1": {
"id": 1,
"email": "sa#gmail.com",
"name": "bass"
}

modifiedDate and lastViewedByMeDate query not woring in Drive API 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.

Categories