Appending values to a google sheet - java

What am i doing wrong? I wanna append values to a sheet:
String valueInputOption = "USER_ENTERED";
String range = "1:1";
String ranges = "Student!2:2";
ValueRange response = service.spreadsheets().values()
.get(spreadsheetId, range)
.execute();
AppendValuesResponse appendValuesResponse = service.spreadsheets()
.values()
.append(spreadsheetId, ranges, response)
.setValueInputOption(valueInputOption)
.execute();
but i get exception:
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"message" : "Request range[Student!2:2] does not match value's
range[Student!A1:Z1]",
"reason" : "badRequest"
} ],
"message" : "Request range[Student!2:2] does not match value's
range[Student!A1:Z1]",
"status" : "INVALID_ARGUMENT"
}
i dont know why my range is wrong...

Check the Reading a single range and Appending values and it should demonstrate how to use the API properly. It seems the error stems from using 2 different ranges. Try to use only one to get rid of this error and work your way from there.

Related

Remove one JSON data from a file of JSON's

my JSON is :
{
"errorMessages" : [ {
"key" : "QUIESCE_FAILURE",
"code" : "12345",
"description" : "User already exists aaa",
"reason" : "Username {user} is already added aaa",
"resolution" : "Please provide a different username aaa",
"more_information" : "more info aaa",
"type" : "error aaa"
}, {
"key" : "DUPLICATE_USERS",
"code" : "3114587",
"description" : "Failed to quiesce database(s)",
"reason" : "Database {database} on host {host} is not accessible",
"resolution" : "Please check that the database is accessible",
"more_information" : "kkkk",
"type" : "error"
} ]
}
i want to delete json with code 3114587 using jackson.
may i get any suggestion?
Thanks in advance.
I suppose you have your JSON contents as a File object.
If you have it as an URL, InputStream, Reader or String,
then just modify the code below by taking another readValue method.
With the classes from packages com.fasterxml.jackson.databind
and com.fasterxml.jackson.databind.node
you can achieve your goal in a straight-forward way.
Read the JSON input, find and remove the array element, and write the JSON output:
File file = ...;
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT); // for pretty print
JsonNode jsonNode = objectMapper.readValue(file, JsonNode.class);
ArrayNode errorMessages = (ArrayNode) jsonNode.get("errorMessages");
for (int i = 0; i < errorMessages.size(); i++) {
ObjectNode errorMessage = (ObjectNode) errorMessages.get(i);
String code = errorMessage.get("code").asText();
if (code.equals("3114587")) {
errorMessages.remove(i); // remove the element
}
}
objectMapper.writeValue(System.out, jsonNode);
delete json[key];
Store your Json object in a variable name json. Find the key that you want to delete and it should work.

Listing teamdrive in google drive sdk with service account

I am trying to list the team drives using service account (domain wide delegation is enabled), when i do so with just the "teamdrives().list()" i am getting a blank response.
{
"kind" : "drive#teamDriveList",
"teamDrives" : [ ]
}
If i use "teamdrives().list().setUseDomainAdminAccess(true).setQ("name='Test'")" or "teamdrives().list().setUseDomainAdminAccess(true)" i am getting below error.
400 Bad Request
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"location" : "q",
"locationType" : "parameter",
"message" : "Invalid Value",
"reason" : "invalid"
} ],
"message" : "Invalid Value"
}
Below is the code block,
InputStream in = new FileInputStream("client_secret.json");
new GoogleCredential();
GoogleCredential credential = GoogleCredential
.fromStream(in)
.createScoped(SCOPES);
Drive _service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
tdllist = _service.teamdrives().list().setUseDomainAdminAccess(true).setQ("name='Test'");
TeamDriveList _tdl = tdllist.execute();
Hoping someone will point what i am doing wrong or an efficient way to do this.
Thanks in advance.
Thanks and Regards
KKG
Update
After some research got to know that "teamdrives().list()" is listing the teamdrive that the user has access to, so i guess that part is working as it is suppose to. But the remaining is still a mystery.

Expected Character for no reason in a JsonPath

Assuming that I have this JSON:
{
"response" : {
"code" : "XXX",
"label" : "Lorem Ipsum",
"items" : [
{
"code" : "200",
"label" : "200 !!!"
},
{
"code" : "300",
"label" : "300 !!!!!"
},
{
"code" : "500",
"label" : "+500 !!!!!"
}]
}
}
I want to get the label of the item when code = 500 (as for example) in Java.
I'm using jayWay Library and this jsonPath:
"$.response.items[?(#.code='500')].label"
I'm getting this error while parsing : Expected character: )
The java code :
public static String getElementValueByJsonPath(String jsonContent, String jsonPath) {
if (checkJsonValidity(jsonContent)) {
String returnedValue ="";
Configuration config = Configuration.defaultConfiguration().addOptions(Option.SUPPRESS_EXCEPTIONS);
try {
returnedValue = ""+JsonPath.using(config).parse(jsonContent).read(jsonPath);
} catch (Exception e) {
System.out.println(e.getMessage());
}
return returnedValue;
}
return null;
Anyone knows why I have this error, and can I bypass it with another library or method.
Thanks
You get the error for a very valid reason, that is not a valid jsonpath query.
If you go to https://jsonpath.herokuapp.com/ ( which uses jayway ) and enter the same data and path you will see this is not a valid jsonpath query for jayway, or two of the other implementations, the only one that does not fail outright does not return what you are expecting. I think you need to go back and re-read the jsonpath documentation as this syntax clearly is not valid.
The correct syntax is $.response.items[?(#.code=='500')].label as the documentation clearly states.
I would not rely on implementations that do not fail on incorrect syntax.

how to compose a request google cloud storage (for parallel upload) using java

I'm trying to upload a file (500 MB) to the google cloud storage. (java)
I created a List of Soource objects and I need to add ObjectPreconditions , ifGenerationMatch () to each of the object in that list.
I don't understand how to use it.
the errors I got from google were not informative at all.
StorageObject metadata = new StorageObject()
.setContentType("text/plain");
List<SourceObjects> sourceObjects = new ArrayList<SourceObjects>();
for (int i = 0; i <= chunkNumber; i++) {
sourceObjects.add( new SourceObjects().setName(objectName + ".chunk" + i) );
}
ComposeRequest composeReq = new ComposeRequest()
.setSourceObjects(sourceObjects)
.setDestination(metadata);
storage.objects().compose(bucketName, fileName,composeReq).execute();
and this is the error:
{
"code" : 404,
"errors" : [ {
"domain" : "global",
"message" : "Not Found",
"reason" : "notFound"
} ],
"message" : "Not Found"

Elastic Search - get records by starting character of a field

I am using Elastic Search Server. I need to get records based on starting character of a field value in source JSON.
JSON:
Index JSON1 : "{\"id\":\"1\",\"message\":\"welcome to elastic search\"}"
Index JSON2 : "{\"id\":\"1\",\"message\":\"Hellow world\"}"
Code:
String selectedCharacter = "w";
PrefixQueryBuilder queryBuilder = QueryBuilders.prefixQuery("message", selectedCharacter);
builder.setQuery(queryBuilder);
By using the above code, I am getting both the records. I need only 'Index JSON1'. Please give any solution to achieve this. Thanks in advance.
By default, Elasticsearch will "tokenize" string fields.
It means that your message fields are considered as a multiple terms fields. For JSON1 : ["welcome", "to", "elastic", "search"] and JSON2 : ["Hellow", "world"].
When you make your query, ElasticSearch will try to match on of the term, that's why you get JSON1 for the "welcome" term et JSON2 for the "world" term.
If you want your message field to be "untokenized" (treated as a single string), you have to explicitly set the mapping of this field to keyword. This is done by using the Mapping API.
You can look at :
the keyword analyzer doc : http://www.elasticsearch.org/guide/reference/index-modules/analysis/keyword-analyzer/
the mapping API doc : http://www.elasticsearch.org/guide/reference/api/admin-indices-put-mapping/
If you need a keyword analyzer but case-insensitive, you need to define a custom analyzer with a lowercase filter (you will probably need to delete and recreate your index for that). Ex :
$ curl -XPUT 'localhost:9200/test/_settings' -d '
{
"index": {
"analysis" : {
"analyzer" : {
"lowercaseAnalyzer": {
"type": "custom",
"tokenizer": "keyword",
"filter": ["lowercase"]
}
}
}
}
}
And then you define your mapping with this custom analyzer instead of keyword :
"message" : {"type" : "string", "analyzer" : "lowercaseAnalyzer"}
You can also test your analyzer using the analyze API. Ex :
$ curl -XGET 'localhost:9200/test/_analyze?analyzer=lowercaseAnalyzer&pretty=true' -d 'Hello world'
{
"tokens" : [ {
"token" : "hello world",
"start_offset" : 0,
"end_offset" : 11,
"type" : "word",
"position" : 1
} ]
}
You can see all the available tokenizers and filters in the analysis documentation : http://www.elasticsearch.org/guide/reference/index-modules/analysis/

Categories

Resources