Defects for specific user story from rally - java

How to retrieve/obtain the defects for particular user story form rally using rally rest api in java?
The following code i have tried.
QueryRequest projectRequest = new QueryRequest("Defect");
projectRequest.setProject(
"https://rally1.rallydev.com/slm/webservice/v2.0/project/"+prjid);
projectRequest.setQueryFilter(new QueryFilter("Requirement", "=", UserR));
//projectRequest.setScopedDown(true);
QueryResponse projectQueryResponse = this.restApi.query(projectRequest);

Assuming
String projectRef = "/project/12345";
String storyRef = "/hierarchicalrequirement/67890";
here is an example that returns defects of user story:
try {
restApi = new RallyRestApi(
new URI(host),
username,
password);
restApi.setApplicationName(applicationName);
QueryRequest defectRequest = new QueryRequest("Defect");
defectRequest.setProject(projectRef);
defectRequest.setFetch(new Fetch(new String[] {"Name", "FormattedID","State", "Priority", "Severity", "Requirement"}));
defectRequest.setLimit(1000);
defectRequest.setScopedDown(false);
defectRequest.setScopedUp(false);
defectRequest.setQueryFilter(new QueryFilter("Requirement", "=", storyRef));
QueryResponse defectQueryResponse = restApi.query(defectRequest);
for (int i=0; i<defectQueryResponse.getResults().size();i++){
JsonObject defectJsonObject = defectQueryResponse.getResults().get(i).getAsJsonObject();
System.out.println("Name: " + defectJsonObject.get("Name") + " State: " + defectJsonObject.get("State") + " Priority: " + defectJsonObject.get("Priority") + " FormattedID: " + defectJsonObject.get("Requirement"));
}
} finally {
if (restApi != null) {
restApi.close();
}
}

Related

Add a custom id when sending a message to receiver twilio message and get custom id while receiving the message java

I have a java requirement where I will send a message from my web server to user. I need to add any custom id in the message headers or session and when the receiver replies back i need to capture that id so that i will identify the message as a specific thread.
I tried to add the custom id in the message but when the receiver responds i am getting a null values always
I am using twilio web hook for receiving messages in java code.
Send SMS Code:
public boolean sendSMS(NotesDTO notes, HttpServletRequest request) {
int accountid = notes.getJobApplicationId();
String jobApplication = String.valueOf(accountid);
HttpSession session = request.getSession(true);
session.setAttribute("counter", notes.getCustomId());
request.setAttribute("counter", notes.getCustomId());
request.getSession().setAttribute("counter", notes.getCustomId());
Twilio.init(environment.getProperty("sendgrid.sms.account.sid"), environment.getProperty("sendgrid.sms.account.token"));
Message message = Message.creator(
new PhoneNumber("+1*********"),
new PhoneNumber("+1*********"),
"Good Morning!! \n"
+ "This is a message from ......\n"
+ "Thank You!!")
.create();
System.out.println("Request Message SID: " + message.getSid());
return true;
}
Receive Message Code:
#RequestMapping(value = "/getMessages", method = RequestMethod.POST)
public GenericResponse getTwilioMessages(HttpServletRequest request, HttpServletResponse response) throws IOException, ForbiddenException {
System.out.println(request.getParameter("Body"));
System.out.println(request.getReader());
String AccountSid = request.getParameter("AccountSid");
String From = request.getParameter("From");
String MessageSid = request.getParameter("MessageSid");
String MessageStatus = request.getParameter("MessageStatus");
String SmsSid = request.getParameter("SmsSid");
String SmsStatus = request.getParameter("SmsStatus");
String ApplicationSid = request.getParameter("ApplicationSid");
String Sid = request.getParameter("Sid");
String sid = request.getParameter("sid");
Object countObject = request.getAttribute("counter");
//String counter = countObject.toString();
System.out.println("AccountSid : " + AccountSid);
System.out.println("From : " + From);
System.out.println("MessageSid : " + MessageSid);
System.out.println("MessageStatus : " + MessageStatus);
System.out.println("SmsSid : " + SmsSid);
System.out.println("SmsStatus : " + SmsStatus);
System.out.println("Counter : " + countObject);
System.out.println("ApplicationSid : " + ApplicationSid);
System.out.println("Sid : " + Sid);
System.out.println("sid : " + sid);
BufferedReader br = new BufferedReader(request.getReader());
String s = null;
String Actualmessage = "";
while ((s=br.readLine())!=null)
{
Actualmessage = Actualmessage + s + "\n";
System.out.println(s);
}
System.out.println("Message : " + Actualmessage);
Map<String, String> map = new HashMap<String, String>();
Enumeration headerNames = request.getHeaderNames();
//Enumeration paramNames = request.getParameterNames();
while (headerNames.hasMoreElements()) {
String key = (String) headerNames.nextElement();
String value = request.getHeader(key);
System.out.println(key + ": " + value);
//map.put(key, value);
}
Body body = new Body.Builder("Hello World!").build();
Message message = new Message.Builder().body(body).build();
Redirect redirect = new Redirect
.Builder("https://demo.twilio.com/welcome/sms/").build();
MessagingResponse responseData = new MessagingResponse.Builder()
.message(message).redirect(redirect).build();
System.out.println("Response: " + responseData.toString());
Enumeration paramNames = request.getParameterNames();
while (paramNames.hasMoreElements()) {
String key = (String) paramNames.nextElement();
String value = request.getParameter(key);
System.out.println(key + ": " + value);
//map.put(key, value);
}
return new GenericResponse("success", null, null);
}```
Counter value is always coming as null

Mocking private method inside a public method

I've made a test of a getStudies method, that has a private method call inside itself. Now, how to mock that call in a test method (see down below)?
It's on a second line in a method for testing String query = setQueryForChangingState(filterParams);. I'll provide additional code, if necessary.
Method for testing
public Object getStudies(FilterInputModel filterParams) {
String query = setQueryForChangingState(filterParams);
logger.info("Get studies query: " + query);
LinkedMultiValueMap<String, String> queryMap = new LinkedMultiValueMap<>();
queryMap.add("q", query);
return Objects.requireNonNull(webClient.post()
.uri("/query")
.header(HttpHeaders.AUTHORIZATION, getSessionId())
.body(BodyInserters.fromMultipartData(queryMap))
.retrieve()
.bodyToMono(QueryResponse.class)
.block())
.data;
}
Private method
private String setQueryForChangingState(FilterInputModel filterParams) {
String query = "SELECT id, " +
"basf_study_id__cr.name__v, " +
"name__v, " +
"state__v, " +
"bas_core__cr.name__v, " +
"object_type__vr.name__v, " +
"external__c, " +
"contract_laboratory__cr.name__v, " +
"object_type__v " +
"FROM study__c " +
"WHERE object_type__vr.name__v = 'External Study' " +
"AND contract_laboratory__c != null " +
"AND state__v = 'study_setup_completed_state__c'";
if (!filterParams.getCores().isEmpty()) {
query = query + " AND bas_core__c CONTAINS('" + String.join("','", filterParams.getCores()) + "')";
}
if (!filterParams.getStudyStartDate().isEmpty()) {
if (filterParams.getStudyStartDate().size() == 1) {
query = query + " AND study_start_date__c = '" + filterParams.getStudyStartDate().get(0) + "'";
} else if (filterParams.getStudyStartDate().size() == 2) {
query = query + " AND study_start_date__c BETWEEN '" + filterParams.getStudyStartDate().get(0) + "' AND '" + filterParams.getStudyStartDate().get(1) + "'";
} else {
logger.info("Date range has to many inputs!");
}
}
return query;
}
My test
#Test
#DisplayName("Test getStudies")
void getStudies() throws IOException {
Path filePath = Path.of("src/test/resources/__files/jsonFile.json");
String body = Files.read(filePath.toFile(), Charset.defaultCharset());
wireMockServer.stubFor(post(urlEqualTo("/api/v16.1/query"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody(body))
);
List<String> cores = List.of("core");
List<String> dates = List.of("startDate");
List<String> objectTypes = List.of("objectType");
inputModel = new FilterInputModel(cores,dates, "state",objectTypes,
"area","analytMethod", "wp", "subDesc", "analytMonitor", "ecoMonitor",
"subType", "analytNeeded", "8e6a2", "methodAvailable",
"analytPhase", "subAvailable","subShipped", "external",
"uploadValidator","contractLab");
Object response = vaultServiceTest.getStudies(inputModel);
QueryResponse jsonBody = new ObjectMapper().readValue(body, QueryResponse.class);
assertEquals(response, jsonBody.data);
I guess it could be done, but I'm not sure how.

Dynamic update query for multiple columns using spring MVC

I am having a JSON data as shown below:
{
"table" : "customer",
"uniqueColumn" : "customer",
"uniqueColVal" : "cust_786",
"columns" :
[{
"column_1" : "column_1 Val",
"column_2" : "column_2 Val",
"column_..." : "column_... Val",
"column_..." : "column_... Val",
"column_..." : "column_... Val",
"column_n" : "column_n Val"
}]
}
I need a query to be executed and should be in the below form
UPDATE customer SET column_1 = 'column_1 Val', column_2 = 'column_2 Val', column_... = 'column_... Val', column_n = 'column_n Val' WHERE customer = 'cust_786';
I am using Spring MVC for processing this and the code I wrote is as follows. It is not complete.
#Override
public Map<String, Object> updateTabColumnValues(Map<String, Object> data)
{
Map<String, Object> response = new HashMap();
try
{
String table= data.get("table").toString();
String uniqueid = data.get("uniqueid").toString();
if (table!=null && uniqueid !=null)
{
String column = null, columnVal = null, updateColumn = null, updateColumnVal = null;
JSONObject jsonObj = new JSONObject(data);
JSONArray columnsToUpdate = jsonObj.getJSONArray("columns");
for (int i = 0; i < columnsToUpdate.length(); i++)
{
if (i == columnsToUpdate.length() - 1)
{
JSONObject json_Obj = columnsToUpdate.getJSONObject(i);
column = json_Obj.keys().next().toString();
columnVal = json_Obj.getString(column).toString();
updateColumn = updateColumn + column.toString();
updateColumnVal = updateColumnVal + " = " + columnVal.toString() + "'";
}
}
System.out.println("UPDATE " + table+ " SET " + updateColumn +" = " + updateColumnVal + " WHERE " + data.get("uniqueColumn").toString() +" = '" + data.get("uniqueColVal").toString() +"';");
}
else
{
response.put("status", false);
LOGGER.info("Failed to get table>>> " + table+ " OR uniqueid >>> " + uniqueid);
}
}
catch (Exception e)
{
response.put("status", false);
LOGGER.error("Error #editLayerAttributeByUniqueID ", e);
System.err.println("Error #editLayerAttributeByUniqueID " + e);
}
return response;
}
It would be very much helpful if someone could help me out here. Thanks in advance.
I could find a satisfying answer at the end. Please follow the below instructions.
You need to import some packages and I am mentioning the Maven repository for the same below. Add the dependency in your pom.xml
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency>
<!-- For PostgreSQL Database connectivity -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.0.RELEASE</version>
</dependency>
Now Import the packages in your Impl file as follows:
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.jdbc.core.JdbcTemplate;
The logic is explained in the below code
public JdbcTemplate getJdbcTemplate()
{
return jdbcTemplate;
}
#Override
//Defines a Map named as updateTabColumnValues to get data from client
public Map<String, Object> updateTabColumnValues(Map<String, Object> data)
{
//Defines a Map named as response to send data to client
Map<String, Object> response = new HashMap();
try
{
String table = data.get("table").toString();
String uniqueColumn = data.get("uniqueColumn").toString();
String uniqueValue = data.get("uniqueValue").toString();
if ((uniqueColumn != null && uniqueValue != null) && table != null)
{
String column;
String columnVal;
String keyValuePair = "";
String query = null;
JSONObject jsonObj = new JSONObject(data);
//Gets values in the key columns to columnsToUpdate
JSONArray columnsToUpdate = jsonObj.getJSONArray("columns");
//Loops each elements with in the array
if (columnsToUpdate.length() > 0)
{
for (int i = 0; i < columnsToUpdate.length(); i++)
{
if (i == columnsToUpdate.length() - 1)
{
//Create Key Value pair without adding comma at the end
JSONObject json_Obj = columnsToUpdate.getJSONObject(i);
column = json_Obj.keys().next();
columnVal = json_Obj.getString(column);
keyValuePair = keyValuePair + column + " = '" + columnVal + "'";
}
else
{
//Create Key Value pair with comma at the end
JSONObject json_Obj = columnsToUpdate.getJSONObject(i);
column = json_Obj.keys().next();
columnVal = json_Obj.getString(column);
keyValuePair = keyValuePair + column + " = '" + columnVal + "' , ";
}
}
int queryValidator = -1;
query = "UPDATE " + table +" SET "+ keyValuePair + " WHERE " + uniqueColumn + " = '" + uniqueValue +"';";
LOGGER.info("Query is >>> " + query);
//Uses getJdbcTemplate() to run query
queryValidator = getJdbcTemplate().update(query);
//Validating the query execution status with database
if (queryValidator >= 0)
{
response.put(stateOfstatus,true);
}
else
{
response.put(stateOfstatus,false);
}
}
else
{
response.put(stateOfstatus, false);
}
}
else
{
response.put(stateOfstatus, false);
LOGGER.info("Failed to get table >>> " + table + " OR uniqueColumn >>> " + uniqueColumn + " OR uniqueValue >>>" + uniqueValue);
}
}
catch (Exception e)
{
response.put(stateOfstatus, false);
LOGGER.error("Error in updateTabColumnValues ", e);
response.put("message", e);
}
return response;
}
This was an RnD related task taken under a special usecase. The above logic perfectly and effectivelty delivers the output.

How to get result of Testcase using RallyAPI?

I am new to Rally API. I have been assigned task to get result of TestCase in java using Rally API. Can someone please help me with a sample program. Also please tell me how to get Workspace name in rally.
Here is a code example based in Rally API Toolkit for Java. Also see WS API documentation for details of TestCase and TestCaseResult objects.
public class GetTestCaseResults {
public static void main(String[] args) throws Exception {
String host = "https://rally1.rallydev.com";
String applicationName = "Example: get Results of TestCase";
String projectRef = "/project/12345"; //user your own project OID
String apiKey = "_abc123";
RallyRestApi restApi = null;
try {
restApi = new RallyRestApi(new URI(host),apiKey);
restApi.setApplicationName(applicationName);
QueryRequest testCaseRequest = new QueryRequest("TestCase");
testCaseRequest.setProject(projectRef);
testCaseRequest.setFetch(new Fetch(new String[] {"FormattedID","Results","LastVerdict"}));
testCaseRequest.setQueryFilter(new QueryFilter("FormattedID", "=", "TC3"));
//testCaseRequest.setLimit(25000);
testCaseRequest.setScopedDown(false);
testCaseRequest.setScopedUp(false);
QueryResponse testCaseResponse = restApi.query(testCaseRequest);
System.out.println("Successful: " + testCaseResponse.wasSuccessful());
System.out.println("Size: " + testCaseResponse.getTotalResultCount());
int totalResults = 0;
for (int i=0; i<testCaseResponse.getResults().size();i++){
JsonObject testCaseJsonObject = testCaseResponse.getResults().get(i).getAsJsonObject();
System.out.println("Name: " + testCaseJsonObject.get("Name") + " FormattedID: " + testCaseJsonObject.get("FormattedID") + " LastVerdict: " + testCaseJsonObject.get("LastVerdict"));
int numberOfResults = testCaseJsonObject.getAsJsonObject("Results").get("Count").getAsInt();
if(numberOfResults > 0) {
totalResults += numberOfResults;
QueryRequest resultsRequest = new QueryRequest(testCaseJsonObject.getAsJsonObject("Results"));
resultsRequest.setFetch(new Fetch("Verdict","Date"));
//load the collection
JsonArray results = restApi.query(resultsRequest).getResults();
for (int j=0;j<numberOfResults;j++){
System.out.println("Name: " + results.get(j).getAsJsonObject().get("Verdict") + results.get(j).getAsJsonObject().get("Date").getAsString());
}
}
}
System.out.println("Total number of results: " + totalResults);
} finally {
if (restApi != null) {
restApi.close();
}
}
}
}

How to retrieve Test Cases associated with the Test Set

I tried to run provided code for jar 2.0.2 and now for 2.0.4 Both times received an error at line: int numberOfTestCases = testSetJsonObject.get("TestCases").getAsJsonArray().size();
Exception in thread "main" java.lang.IllegalStateException: This is not a JSON Array. at com.google.gson.JsonElement.getAsJsonArray(JsonElement.java:106) at GetTCofTS.main(GetTCofTS.java:50)
I can overcome this error (since it is really not an array that is coming back) , but it won't resolve my problem, that I am trying to get not only the number of TestCases associated with the current TestSet, but list of TestCases - at least their formatted ID. Is it a bag in Rally?
public class GetTCofTS {
public static void main(String[] args) throws Exception {
String host = "https://rally1.rallydev.com";
String username = "user#co.com";
String password = "secret";
String applicationName = "RESTExampleFindTestCasesOfTestSet";
String workspaceRef = "/workspace/1111";
String projectRef = "/project/2222";
String wsapiVersion = "1.43";
RallyRestApi restApi = null;
try {
restApi = new RallyRestApi(
new URI(host),
username,
password);
restApi.setApplicationName(applicationName);
QueryRequest testSetRequest = new QueryRequest("TestSet");
testSetRequest.setWorkspace(workspaceRef);
restApi.setWsapiVersion(wsapiVersion);
testSetRequest.setFetch(new Fetch(new String[] {"Name", "TestCases", "FormattedID"}));
testSetRequest.setQueryFilter(new QueryFilter("Name", "=", "someTS"));
QueryResponse testSetQueryResponse = restApi.query(testSetRequest);
System.out.println("Successful: " + testSetQueryResponse.wasSuccessful());
System.out.println("Size: " + testSetQueryResponse.getTotalResultCount());
for (int i=0; i<testSetQueryResponse.getResults().size();i++){
JsonObject testSetJsonObject = testSetQueryResponse.getResults().get(i).getAsJsonObject();
System.out.println("Name: " + testSetJsonObject.get("Name") + " ref: " + testSetJsonObject.get("_ref").getAsString() + " Test Cases: " + testSetJsonObject.get("TestCases"));
int numberOfTestCases = testSetJsonObject.get("TestCases").getAsJsonArray().size();
System.out.println(numberOfTestCases);
if(numberOfTestCases>0){
for (int j=0;j<numberOfTestCases;j++){
System.out.println(testSetJsonObject.get("TestCases").getAsJsonArray().get(j).getAsJsonObject().get("FormattedID"));
}
}
}
} finally {
if (restApi != null) {
restApi.close();
}
}
}
}
v2.0 is the preferred version going forward. The following small tweaks should get you up and going.
Instead of this (which works in 1.43 because the collection is returned):
int numberOfTestCases = testSetJsonObject.get("TestCases").getAsJsonArray().size();
if(numberOfTestCases>0) {
for (int j=0;j<numberOfTestCases;j++) {
System.out.println(testSetJsonObject.get("TestCases").getAsJsonArray().get(j).getAsJsonObject().get("FormattedID"));
}
}
Do this:
//TestCases is an object with a Count and a ref to load the collection
int numberOfTestCases = testSetJsonObject.getAsJsonObject("TestCases").get("Count").getAsInt();
if(numberOfTestCases > 0) {
QueryRequest testCaseRequest = new QueryRequest(testSetJsonObject.getAsJsonObject("TestCases"));
testCaseRequest.setFetch(new Fetch("FormattedID"));
//load the collection
JsonArray testCases = restApi.query(testCaseRequest).getResults();
for (int j=0;j<numberOfTestCases;j++){
System.out.println(testCases.get(j).getAsJsonObject().get("FormattedID").getAsString());
}
}

Categories