I am trying to build a Response object with a information I am getting back from a database. The information I am getting back is in a Change object:
The change.getDocument() coming back is:
{"testSolution":false,"solutionId":333,"clientId":4018593,"firewall":false,"pod":"pod3.dmy3","networkPolicy":{"speed":"1","subnets":{"nat":{"vlan":3004,"cidr":["110.168.0.0/24"]},"private":{"vlan":3004,"cidr":["15.10.1.128/25"]}}}}
So I am creating a Response like this:
return Response.status(422).location(location).entity(changeRequest).build();
In the unit test I do this:
String responseJson = response.readEntity(String.class);
System.out.println("The response is: " + responseJson);
For testing, but I get this result:
The response is: {"object_id" : 333,"object_type" : "class com.entities.Solution", "operation" : "", "revision" : 0, "remote_user" : "", "remote_host" : "", "created" : "", "published" : "", "comment" : "HTTP Status Code 422", "error" : "HTTP Status Code 422, there is a pending change request for this Solution. Replying with pending ChangeRequest", "document" : {} }
Everything is as expected, but the document node contains no information. Am I building the Response object correctly?
Try to return it in this way:
Response.status(Status.OK).type(MediaType.APPLICATION_JSON)
.entity(changeRequest).build();
Related
So I am trying to create a simple webservice post that consumes json. But I am geting the error RESTEASY002010: Failed to execute: javax.ws.rs.NotSupportedException: RESTEASY003065: Cannot consume content type
My webservice:
#POST
#Produces(MediaType.APPLICATION_XML)
#Path("teste1")
#Consumes(MediaType.APPLICATION_JSON)
public Response teste1(String product) {
String result = "Product created : " + product;
System.out.println("resultado");
System.out.println(result);
return Response.ok() //200
.entity("<erro> none </erro>")
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
.header("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With").build();
}
I also tried to do:
#Consumes("application/json")
But I am getting the same error. I can make it work if I do:
#Consumes("*/*")
But I can't understand why it doesn't work when I say it consumes json. To test the webservice I am using https://apitester.com/. With the folowing Post Data:
{
"key" : "value",
"array" : [
{ "key" : 1 },
{ "key" : 2, "dictionary": {
"a": "Apple",
"b": "Butterfly",
"c": "Cat",
"d": "Dog"
} },
{ "key" : 3 }
]
}
In general the
#Consumes("application/json")
specifies a content media type which webservice can handle.
But also you may need to explicitly specify an appropriate type in the Content-Type header for your request.
I am not familiar with the https://apitester.com but probably it does not send the Content-Type header by default
In such case your server can treat the request body as a plain text, for instance. That request would not be routed to your endpoint, because it is not designed for the plain text.
Setting the #Consumes(*/*) fixes that problem, because the wrong media type matches that pattern as well.
Could you please ensure that you sends the Content-Type: application/json with your POST 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"
}
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.
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
I'm doing Java web application. A back-end method sends a JSON list but how can I access it from front-end?
This is a sample of the JSON list which is returning from back-end method.
[ { "completedDate" : null,
"completenessLevel" : 0,
"priority" : 0,
"startedDate" : 1405621923000,
"toBeCompleted" : 1405621923000,
"userName" : "prasad",
"userTaskDiscription" : "Task1 desc",
"userTaskId" : 25,
"userTaskName" : "Task1"
},
{ "completedDate" : null,
"completenessLevel" : 0,
"priority" : 0,
"startedDate" : 1405704875000,
"toBeCompleted" : 1405704875000,
"userName" : "prasad",
"userTaskDiscription" : "Task2 desc",
"userTaskId" : 26,
"userTaskName" : "Task2"
}
]
Assuming you are using jQuery to make your JSON requests you can access JSON list in the success method of the ajax function. Your success method could like
success:function(response){
console.log(response[0].userName);
}
This would print prasad from the first object in the JSON list.