How to bulk update test run results with test case IDs (TestRail Java Client)? - testrail

How do I bulk update test run results with test case IDs using TestRail Java Client?
Here is a sample bulk update request from API reference for add_results_for_cases().
{
"results": [
{
"case_id": 1,
"status_id": 5,
"comment": "This test failed",
"defects": "TR-7"
},
{
"case_id": 2,
"status_id": 1,
"comment": "This test passed",
"elapsed": "5m",
"version": "1.0 RC1"
},
..
{
"case_id": 1,
"assignedto_id": 5,
"comment": "Assigned this test to Joe"
}
..
]
}

The API call
public static void addResultsForCasesAllPass(int testRunId, int... testIds)
{
APIClient client = new APIClient(BASE_URL);
client.setUser(USER);
client.setPassword(API_KEY);
JSONArray response = null;
try
{
Map data = new HashMap();
List cases = new ArrayList();
data.put("results", cases);
for ( int testId : testIds )
{
Map singleCase = new HashMap();
singleCase.put("case_id", "" + testId);
singleCase.put("status_id", "" + 5);
cases.add(singleCase);
}
String responseReq = JSONValue.toJSONString(data);
Log.d(TAG, responseReq);
Object object =
client.sendPost("add_results_for_cases/"
+ testRunId, data);
response =
(JSONArray) client.sendPost("add_results_for_cases/"
+ testRunId, data);
Log.d(TAG,"response = "+response.toJSONString());
}
catch ( IOException e )
{
e.printStackTrace();
}
catch ( APIException e )
{
e.printStackTrace();
}
}
and for variables
public static final String USER = "firstName.lastName#company.com";
public static final String API_KEY = "/asdsdsd-k9yTR8cxxxxd5uj";
public static final String BASE_URL = "https://my.testRail.io/";
also remember to enable API key via admin tab in test rail site

Related

Jackson adds empty object in front of arrayList during deserialization

I have a simple POJO (ProviderModel).
When I deserialize a list of this objects (see code: List providers) an empty object is added in front of the JSON.
I am using Jackson 1.9.13 ans Spring 3.0.7
#RequestMapping(value = "/provider/update", method = RequestMethod.POST)
#ResponseStatus(HttpStatus.OK)
public List<ProviderModel> updateLongList(#RequestBody ArrayList<Map<String, Object>> models,
HttpServletRequest request) {
List<ProviderModel> providers = new ArrayList<ProviderModel>();
for (Map<String, Object> model : models) {
ProviderModel providerModel = new ProviderModel();
providerModel.setId((int) model.get("id"));
long rfpId = Long.parseLong((String) request.getSession().getAttribute("rfpId"));
MYLOG.info("rfpId = " + rfpId);
long listId = ProviderListLocalServiceUtil.findLongListforRfP(rfpId);
User user = null;
long userId = 0;
try {
user = OsdeUserUtil.getUserFromCookies(request);
userId = user.getUserId();
} catch (PortalException | SystemException | EncryptorException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
long providerId = providerModel.getId();
// add to LongList
try {
ProviderListEntryServiceUtil.addProviderListEntryByListId(listId, userId, providerId);
providers.add(providerModel);
} catch (SystemException | PortalException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MYLOG.info("Provider hinzugefügt " + model.get("id") + "/" + model.get("name"));
}
return providers;
}
And this is the response:
{}
&& {
"providerModelList": [{
"id": 1502,
"name": null,
"location": null,
"description": null,
"imagePath": null,
"detailUrl": null,
"providerStatus": null
}
]
}
Any ideas or hints?
I found the mistake!
#RespondBody is missing in the method signature:
#RequestMapping(value = "/provider/update", method = RequestMethod.POST)
#ResponseStatus(HttpStatus.OK)
public #RespondBody List<ProviderModel> updateLongList(#RequestBody ArrayList<Map<String, Object>> models,
HttpServletRequest request) {...}

JSON encode accented charters for mirrorapi

I send a message with the mirror api from an android app, but when I receive the timeline on my glass I can't see the accented charters like "è"
This is the string:
String text_message = "try this accented char è";
This is the creation of the JSON :
String html_message = String.format(
"<article>" +
"<section>" +
"<div class=text-x-small>" +
"<p class=blue>%s" +
"<p>%s</p>" +
"</p></div>" +
"</section>" +
"<footer>" +
"<div>%s</div>" +
"</footer>" +
"</article>"
,name,text_message,app_name);
JSONObject notification = new JSONObject();
notification.put("level", "DEFAULT"); // Play a chime
JSONArray menuitems = new JSONArray();
JSONObject reqObj = new JSONObject();
reqObj.put("action","TOGGLE_PINNED");
menuitems.put(reqObj);
reqObj = new JSONObject();
reqObj.put( "action", "READ_ALOUD" );
menuitems.put( reqObj );
reqObj = new JSONObject();
reqObj.put( "action", "VOICE_CALL" );
menuitems.put( reqObj );
reqObj = new JSONObject();
reqObj.put( "action", "DELETE" );
menuitems.put( reqObj );
json = new JSONObject();
json.put("html", html_message);
json.put("speakableText",message);
json.put("menuItems",menuitems);
json.put("notification", notification);
MyLog.log("JSON TO SEND: " + json.toString());
new sendJSON().execute();
This is the AsyncTask that send the JSON to the mirror api :
private class sendJSON extends AsyncTask<String, Integer, Double> {
#Override
protected Double doInBackground(String... params) {
try {
postData();
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
protected void onPreExecute(){
}
protected void onPostExecute(Double result){
//pb.setVisibility(View.GONE);
//MyLog.log("Richiesta al server inviata GET CONTACTS");
}
protected void onProgressUpdate(Integer... progress){
//pb.setProgress(progress[0]);
}
public void postData() throws URISyntaxException, UnsupportedEncodingException {
HttpParams params_ = new BasicHttpParams();
params_.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params_, "utf-8");
String BASE_URL = "https://www.googleapis.com/mirror/v1/";
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient(params_);
HttpPost httppost = new HttpPost();
httppost.setURI(new URI(BASE_URL + "timeline"));
httppost.addHeader("Authorization", String.format("Bearer %s", mAuthToken));
httppost.addHeader("Content-Type", "application/json; charset=UTF-8");
httppost.setEntity(new StringEntity(json.toString()));
try {
// Execute HTTP Post Request
final HttpResponse response = httpclient.execute(httppost);
MyLog.log("RESPONSE: " + EntityUtils.toString(response.getEntity()));
} catch (ClientProtocolException e) {
} catch (IOException e) {
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is the response:
RESPONSE: {
"kind": "mirror#timelineItem",
"id": "ea3f9046-c0a2-4ed5-8a02-f6432f1XXX43",
"selfLink": "https://www.googleapis.com/mirror/v1/timeline/ea3f9046-c0a2-4ed5-8a02-f6432f1XXX43",
"created": "2013-12-22T20:28:37.278Z",
"updated": "2013-12-22T20:28:37.278Z",
"etag": "1387744117278",
"html": "\u003carticle\u003e\u003csection\u003e\u003cdiv class=\"text-x-small\"\u003e\u003cp class=\"blue\"\u003e21:28\u003csub\u003e PM\u003c/sub\u003e\u003c/p\u003e\u003cp class=\"yellow\"\u003eMatteo Valenza\u003cp\u003eTry this accented char \u003c/p\u003e\u003c/p\u003e\u003c/div\u003e\u003c/section\u003e\u003cfooter\u003e\u003cdiv\u003eWhatsGlass\u003c/div\u003e\u003c/footer\u003e\u003c/article\u003e",
"speakableText": "try this accented char ",
"menuItems": [
{
"action": "READ_ALOUD"
},
{
"action": "DELETE"
}
],
"notification": {
"level": "DEFAULT"
}
}
Why i don't see the accented char? How can I encode it in the correct way?
Problem solved !
escape the string to html :)
message = Html.escapeHtml(message);

How do I iterate over a JSON response using Jackson API (of a List inside a List)?

How do I iterate over a JSON response in Java using Jackson API? In other words, if the response has a list and inside that list is another list ( in this case called 'weather') , then how do I get the temperature?
Here is an example of what I am trying to iterate through:
{
"message":"like",
"cod":"200",
"count":3,
"list":[
{
"id":2950159,
"name":"Berlin",
"coord":{
"lon":13.41053,
"lat":52.524368
},
"weather":[
{
"id":804,
"main":"Clouds",
"description":"overcast clouds",
"temp":74
}
]
},
{
"id":2855598,
"name":"Berlin Pankow",
"coord":{
"lon":13.40186,
"lat":52.56926
},
"weather":[
{
"id":804,
"main":"Clouds",
"description":"overcast clouds",
"temp":64
}
]
}
]
}
And here is the code I am trying to use, which doesn't work, because I can only iterate through the first item:
try {
JsonFactory jfactory = new JsonFactory();
JsonParser jParser = jfactory.createJsonParser( new File("test.json") );
// loop until token equal to "}"
while ( jParser.nextToken() != JsonToken.END_OBJECT ) {
String fieldname = jParser.getCurrentName();
if ( "list".equals( fieldname ) ) { // current token is a list starting with "[", move next
jParser.nextToken();
while ( jParser.nextToken() != JsonToken.END_ARRAY ) {
String subfieldname = jParser.getCurrentName();
System.out.println("- " + subfieldname + " -");
if ( "name".equals( subfieldname ) ) {
jParser.nextToken();
System.out.println( "City: " + jParser.getText() ); }
}
}
}
jParser.close();
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("-----------------");
You are parsing the JSON when Jackson is meant to do it for you. Don't do this to yourself.
One option is to create a DTO (Data Transfer Object) that matches the format of your JSON
class Root {
private String message;
private String cod;
private int count;
private List<City> list;
// appropriately named getters and setters
}
class City {
private long id;
private String name;
private Coordinates coord;
private List<Weather> weather;
// appropriately named getters and setters
}
class Coordinates {
private double lon;
private double lat;
// appropriately named getters and setters
}
class Weather {
private int id;
private String main;
private String description;
private int temp;
// appropriately named getters and setters
}
Then use an ObjectMapper and deserialize the root of the JSON.
ObjectMapper mapper = new ObjectMapper();
Root root = mapper.readValue(yourFileInputStream, Root.class);
You can then get the field you want. For example
System.out.println(root.getList().get(0).getWeather().get(0).getTemp());
prints
74
The alternative is to read your JSON in as a JsonNode and traverse it until you get the JSON element you want. For example
JsonNode node = mapper.readTree(new File("text.json"));
System.out.println(node.get("list").get(0).get("weather").get(0).get("temp").asText());
also prints
74
Based on the answer that Sotirios Delimanolis gave me, here was my solution:
ObjectMapper mapper = new ObjectMapper();
JsonFactory jfactory = mapper.getFactory();
JsonParser jParser;
try {
jParser = jfactory.createParser( tFile );
JsonNode node = mapper.readTree( jParser);
int count = node.get("count").asInt();
for ( int i = 0; i < count; i++ ) {
System.out.print( "City: " + node.get("list").get(i).get("name").asText() );
System.out.println( " , Absolute temperature: " +
node.get("list").get(i).get("main").get("temp").asText() );
}
jParser.close();
} catch (IOException e) {
e.printStackTrace();
}
I know it's old. This is my solution if you need to convert a JSON into a list and you don't have direct setters in your object.
Let's say that you have this JSON structure of 'Players':
JSON:
{
"Players":
[
{
"uid": 1, "name": "Mike",
"stats": {"shots" : 10, "hits": 5}
},
{
"uid": 2, "name": "John",
"stats": {"shots": 4, "hits": 1}
}
]
}
getListOfPlayersFromJson:
public static List<Player> getListOfPlayersFromJson(String json) {
List<Player> players = new ArrayList<>();
try {
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(json);
root.at("/Players").forEach(node -> {
Player p = getPlayerFromNode(node);
players.add(p);
});
} catch (IOException e) {
e.printStackTrace();
}
return players;
}
getPlayerFromNode:
public static Player getPlayerFromNode(JsonNode node) {
Player player = new Player();
player.setUid(node.at("/uid").longValue());
player.setName(node.at("/name").asText());
player.setStats(
node.at("/stats/shots").asInt(),
node.at("/stats/hits").asInt()
);
return player;
}

Array retrieval from JSON file

I have an array in JSON file which look like this
{ "fields": [
{
"name": "order_id",
"type": "INTEGER",
"position": 0
},
{
"name": "district_id",
"type": "INTEGER",
"position": 1
}]
}
I'm using a TREE MODEL in retrieving the contents of the array "fields" and my code looks like this ..
public static void main(String[] args) throws JsonParseException, IOException {
File jsonFile = new File("metadata.json");
String theJsonString = jsonFile.toString();
String name = null;
String type =null;
int position = 0;
ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
JsonNode rootNode = mapper.readTree(theJsonString);
JsonNode fields = rootNode.get("fields");
if (fields != null) {
for (int i = 0; i < fields.size(); i ++) {
if(fields.has("name"))
name = fields.get("name").getTextValue();
if(fields.has("type"))
type = fields.get("type").getTextValue();
if(fields.has("position"))
position = fields.get("position").getIntValue();
System.out.println(name);
}
}
}
I get the following error during the run time ::
Exception in thread "main" org.codehaus.jackson.JsonParseException: Unexpected character ('/' (code 47)): maybe a (non-standard) comment? (not recognized as one since Feature 'ALLOW_COMMENTS' not enabled for parser)
at [Source: java.io.StringReader#3eed2cab; line: 1, column: 2]
at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:1432)
at org.codehaus.jackson.impl.JsonParserMinimalBase._reportError(JsonParserMinimalBase.java:385)
at org.codehaus.jackson.impl.JsonParserMinimalBase._reportUnexpectedChar(JsonParserMinimalBase.java:306)
at org.codehaus.jackson.impl.ReaderBasedParser._skipComment(ReaderBasedParser.java:1498)
at org.codehaus.jackson.impl.ReaderBasedParser._skipWSOrEnd(ReaderBasedParser.java:1474)
at org.codehaus.jackson.impl.ReaderBasedParser.nextToken(ReaderBasedParser.java:362)
at org.codehaus.jackson.map.ObjectMapper._initForReading(ObjectMapper.java:2761)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2709)
at org.codehaus.jackson.map.ObjectMapper.readTree(ObjectMapper.java:1533)
at metadata.JSONParser.main(JSONParser.java:32)
I have just started working with JSON and hence unable to find a solution. Could anybody help me resolve this?
If you want the contents of the file metadata.json then calling toString on the file will not give you that. Instead it will give you a string which holds the path to the filename.
Instead create a FileInputStream from the File like so:
FileInputStream fis = new FileInputStream(jsonFile);
The you can use it with the mapper
JsonNode rootNode = mapper.readTree(fis);
You might also want to call fields.get(i) when you are iterating through the array to access each JsonNode contained in the array.
I have the same problem and I fixed the problem finally by this code to get the JsonParser object.
FileInputStream fis = new FileInputStream(path);
JsonParser jp = new JsonFactory().createParser(fis);
I had the same problem few days ago. My JSON have the next syntax:
{ "boxes": [
{
"name": "redBox.png",
"version": 15
},
{
"name": "blueBox.png",
"version": 9
}
]
}
I had to create method which return me POJO classes with box versions. My solution is follow:
private static List<DataVersion> receiveDataVersions() throws IOException
{
String path = System.getProperty( "user.dir" ) + File.separator +
"versions.json";
List<DataVersion> versions = new ArrayList<>();
JsonNode folder = null;
try( InputStream stream = new FileInputStream( path ) )
{
folder = new ObjectMapper().readTree( stream );
}
JsonNode boxes = folder.get( "inst" );
boxes.forEach( version -> versions.add( new DataVersion(
version.get( "name" ).getTextValue(),
version.get( "version" ).getIntValue() ) ) );
return versions;
}
POJO is as follows:
public class DataVersion
{
private String name;
private int version;
public DataVersion() {
}
public DataVersion(String name, int version) {
this.name = name;
this.version = version;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getVersion() {
return version;
}
public void setVersion(int version){
this.version=version;
}
#Override
public String toString()
{
return "DataVersion [" + "name='" + name + '\'' + ", version=" +
version + ']';
}
}
try this in your code
jsonFactory.enable(JsonParser.Feature.ALLOW_COMMENTS);

Resolving Nested JSON issue using Spring-Hibernate

I am using spring mvc and jackson for my extjs application and stuck at some thing similar.
I have my list of records returned from DB using Hibernate.
DAO class:
#SuppressWarnings("unchecked")
#Override
public List<CandidateStatus> getcandidateStatus() {
//return hibernateTemplate.find("select candstat.candidate.firstName as firstName,candstat.candidate.lastName as lastName,candstat.candidate.email as email,candstat.statusTitle as statusTitle,candstat.requirement.client.clientName as clientName,candstat.requirement.reqTitle as reqTitle from CandidateStatus as candstat");
return hibernateTemplate.find("from CandidateStatus");
//return hibernateTemplate.find("from CandidateStatus candstat left outer join candstat.candidate left outer join candstat.requirement left outer join candstat.requirement.client");
//return hibernateTemplate.find("from Candidates as cands inner join cands.candidateStats");
}
**Service class**
public List<CandidateStatus> getCandidateStatusList()
{
//return candidatesDAO.getCandidates();
return candidatesDAO.getcandidateStatus();
}
Controller class
#RequestMapping(value="/candidates/view.action")
public #ResponseBody Map<String,? extends Object> view() throws Exception {
try{
//List<Candidates> candidates = candidatesService.getCandidatesList();
List<CandidateStatus> candidatestatus = candidatesService.getCandidateStatusList();
return getMap(candidatestatus);
} catch (Exception e) {
return getModelMapError("Error retrieving Candidates from database.");
}
private Map<String,Object> getMap(List<CandidateStatus> candidatestatus){
Map<String,Object> modelMap = new HashMap<String,Object>(3);
modelMap.put("success", true);
modelMap.put("total", candidatestatus.size());
modelMap.put("data", candidatestatus);
return modelMap;
}
private Map<String,Object> getModelMapError(String msg){
Map<String,Object> modelMap = new HashMap<String,Object>(2);
modelMap.put("message", msg);
modelMap.put("success", false);
return modelMap;
}
Before adding it to the map I want to format the JSON in a required format as per my application.I get the format in a nested manner which is not accepted by extjs.
{
"data": [
{
"id": 29,
"requirement": {
"id": 27,
"client": {
"id": 12,
"clientName": "HireCraft"
},
"clientId": 12,
"reqTitle": "Support Engineer"
},
"reqid": 27,
"resid": 45,
"candidate": {
"id": 45,
"firstName": "Vikram",
"lastName": "",
"email": "bj.vikram#gmail.com"
},
"statusTitle": "Shortlisted"
}],
"success":true,
"total":7668
}
I want the json to be flat file like this without nesting.
"data": [ {
"clientName": "ABC"
"firstName": "Suynil",
"lastName": "Seelam",
"email": "ss.seelam#gmail.com",
"reqTitle": "Java"}]success:true,total:768}
Can you please guide me how I can achive this.I have stuglling for long over this issue!
I tried a bit and getting something likethis.
private Map<String,Object> getMap(List<CandidateStatus> candidatestatus){
Map<String,Object> modelMap = new HashMap<String,Object>(3);
Map<String,Object> candDetails = new HashMap<String,Object>(7);
Iterator<CandidateStatus> iterator=candidatestatus.iterator();
CandidateStatus astring = new CandidateStatus();
String Client;
String Fname;
String Lname;
String Email;
String Phone;
String Status;
String Require;
while(iterator.hasNext())
{
astring = iterator.next();
/*System.out.println(astring.getCandidate().getFirstName());
System.out.println(astring.getCandidate().getLastName());
System.out.println(astring.getCandidate().getEmail());
System.out.println(astring.getStatusTitle());
System.out.println(astring.getRequirement().getReqTitle());*/
Client = astring.getRequirement().getClient().getClientName();
Fname = astring.getCandidate().getFirstName();
Lname = astring.getCandidate().getLastName();
Email = astring.getCandidate().getEmail();
Phone = astring.getCandidate().getPhone();
Status = astring.getStatusTitle();
Require= astring.getRequirement().getReqTitle();
candDetails.put("clientName",Client);
candDetails.put("firstName",Fname);
candDetails.put("lastName",Lname);
candDetails.put("email",Email);
candDetails.put("phone",Phone);
candDetails.put("statusTitle",Status);
candDetails.put("reqTitle",Require);
//jsonMap.put("root", candDetails);
//System.out.println(jsonMap);
}
//System.out.println("----"+candDetails+"----");
modelMap.put("success", true);
modelMap.put("total",candDetails.size());
modelMap.put("data",candDetails );
return modelMap;
Now when I try to add candDetails to the modelMap I get only the LAST record.Why???
Thanks
I don't think your second example is valid JSON, at least according to json.org. An object is defined as:
an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).
That tells me that JSON has to start with a '{' and end with a '}'.
Your approach will work, if you change you work with map candDetails witch is kinda silly. In your loop you put data with same key, thats why you get data with last iterate.
I suggest you to write custom wrapper object(lets call it CandidateStatusWrapper and build there all structure you need. Then you just return list of wrapped objects.
Wrapper example:
class CandidateStatusWrapper {
String clientName;
String firstName;
public CandidateStatusWrapper(String clientName, String firstName) {
this.clientName = clientName;
this.firstName = firstName;
}
}
Change your map:
Map<String,Object> candDetails = new HashMap<String,Object>(7);
into list:
List<CandidateStatusWrapper> = new ArrayList<CandidateStatusWrapper >();
Loop in Controller:
while(iterator.hasNext())
{
astring = iterator.next();
Client = astring.getRequirement().getClient().getClientName();
Fname = astring.getCandidate().getFirstName();
CandidateStatusWrapper wrapped = new CandidateStatusWrapper(Client, Fname);
candDetails.add(wrapped);
}