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();
}
}
}
}
Related
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 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();
}
}
Basics of this program;
Runs a webcrawler based on PerentUrl and Keyword specified by the user in Controller (main). If the Keyword is found in the page text, the Url is then saved to an array list;
ArrayList UrlHits = new ArrayList();
Once the crawl is complete the program will call methods from the WriteFile class in the main to write a html file containing all the UrlHits.
WriteFile f = new WriteFile();
f.openfile(Search);
f.StartHtml();
f.addUrl(UrlHits);
f.EndHtml();
f.closeFile();
All but f.addUrl work correctly, creating a html file with the correct name and directory. But none of the strings from the ArrayList output to the file.
public static void main(String[] args) throws Exception {
RobotstxtConfig robotstxtConfig2 = new RobotstxtConfig();
String crawlStorageFolder = "/Users/Jake/Documents/sem 2/FYP/Crawler/TestData";
int numberOfCrawlers = 1;
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(crawlStorageFolder);
config.setMaxDepthOfCrawling(21);
config.setMaxPagesToFetch(24);
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
Scanner perentUrl = new Scanner(System.in);
System.out.println("Enter full perant Url... example. http://www.domain.co.uk/");
String Url = perentUrl.nextLine();
Scanner keyword = new Scanner(System.in);
System.out.println("Enter search term... example. Pies");
String Search = keyword.nextLine();
System.out.println("Searching domain :" + Url);
System.out.println("Keyword:" + Search);
ArrayList<String> DomainsToInv = new ArrayList<String>();
ArrayList<String> SearchTerms = new ArrayList<String>();
ArrayList<String> UrlHits = new ArrayList<String>();
DomainsToInv.add(Url);
SearchTerms.add(Search);
controller.addSeed(Url);
controller.setCustomData(DomainsToInv);
controller.setCustomData(SearchTerms);
controller.start(Crawler.class, numberOfCrawlers);
WriteFile f = new WriteFile();
f.openfile(Search);
f.StartHtml();
f.addUrl(UrlHits);
f.EndHtml();
f.closeFile();
}
}
public class Crawler extends WebCrawler {
#Override
public void visit(Page page) {
int docid = page.getWebURL().getDocid();
String url = page.getWebURL().getURL();
String domain = page.getWebURL().getDomain();
String path = page.getWebURL().getPath();
String subDomain = page.getWebURL().getSubDomain();
String parentUrl = page.getWebURL().getParentUrl();
String anchor = page.getWebURL().getAnchor();
System.out.println("Docid: " + docid);
System.out.println("URL: " + url);
System.out.println("Domain: '" + domain + "'");
System.out.println("Sub-domain: '" + subDomain + "'");
System.out.println("Path: '" + path + "'");
System.out.println("Parent page: " + parentUrl);
System.out.println("Anchor text: " + anchor);
if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
String text = htmlParseData.getText();
String html = htmlParseData.getHtml();
List<WebURL> links = htmlParseData.getOutgoingUrls();
System.out.println("Text length: " + text.length());
System.out.println("Html length: " + html.length());
System.out.println("Number of outgoing links: " + links.size());
}
Header[] responseHeaders = page.getFetchResponseHeaders();
if (responseHeaders != null) {
System.out.println("Response headers:");
for (Header header : responseHeaders) {
System.out.println("\t" + header.getName() + ": " + header.getValue());
}
}
System.out.println("=============");
ArrayList<String> SearchTerms = (ArrayList<String>) this.getMyController().getCustomData();
ArrayList<String> UrlHits = (ArrayList<String>) this.getMyController().getCustomData();
for (String Keyword : SearchTerms) {
System.out.println("Searching Keyword: " + Keyword);
HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
int KeywordCounter = 0;
String pagetext = htmlParseData.getText();
Pattern pattern = Pattern.compile(Keyword);
Matcher match1 = pattern.matcher(pagetext);
if (match1.find()) {
while (match1.find()) {
KeywordCounter++;
}
System.out.println("FOUND " + Keyword + " in page text. KeywordCount: " + KeywordCounter);
UrlHits.add(url);
for (int i = 0; i < UrlHits.size(); i++) {
System.out.print(UrlHits.get(i) + "\n");
System.out.println("=============");
}
} else {
System.out.println("Keyword search was unsuccesful");
System.out.println("=============");
}
}
}
}
public class WriteFile {
private Formatter x;
public void openfile(String keyword) {
try {
x = new Formatter(keyword + ".html");
} catch (Exception e) {
System.out.println("ERROR");
}
}
public void StartHtml() {
x.format("%s %n %s %n %s %n %s %n %s %n ", "<html>", "<head>", "</head>", "<body>", "<center>");
}
public void addUrl(ArrayList<String> UrlHits) {
for (String list : UrlHits) {
x.format("%s%s%s%s%s%n%s%n", "", list, "", "<br>");
}
}
public void EndHtml() {
x.format("%s %n %s %n %s %n", "</center>", "</body>", "</html>");
}
public void closeFile() {
x.close();
}
}
Apologies for the class headers outside the code blocks its a little fiddly. I have tried a few different "for" statements to get the method to output the array list but it doesn't seem to be having it. The strings are being added to the array list as i can call them using a for loop in the main. But when i pass the array list to the method addUrl, it comes up with squat. is there an easier way to use arraylists using formatters and .format?
Thanks for you help
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());
}
}
I tried to request a large amount of data from freebase. But I got error message "HTTP response code: 403". Did anyone have similar problem before?
Here is my code
private static final String service_url = "https://www.googleapis.com/freebase/v1/mqlread";
public static void main(String[] args)
{
try
{
String cursor = "";
String urlStr_initial = service_url + "?query=" + URLEncoder.encode(getQuery(), "UTF-8") + "&cursor";
URL url = new URL(urlStr_initial);
List<Freebase> list = new ArrayList<Freebase>();
Freebase f_b;
do
{
HttpURLConnection url_con = (HttpURLConnection)url.openConnection();
url_con.addRequestProperty("User-Agent", "Mozilla/4.76");
StringBuilder str_builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(url_con.getInputStream()));
String line;
while((line = reader.readLine()) != null)
{
str_builder.append(line);
}
String response = str_builder.toString();
JSONObject j_object = new JSONObject(response);
if(j_object.has("result"))
{
JSONArray j_array = j_object.getJSONArray("result");
for(int i = 0; i < j_array.length(); i++)
{
JSONObject j_o = j_array.getJSONObject(i);
if(j_o.has("id") == true && j_o.has("name"))
{
String id = j_o.getString("id");
String name = j_o.getString("name");
System.out.println("ID: " + id + " / Name:" + name);
f_b = new Freebase(id, name);
if(f_b != null)
{
list.add(f_b);
}
else
{
System.out.println("Null value in Freebase");
}
}
}
}
else
{
System.out.println("There is no \"result\" key in JASON object");
}
if(j_object.has("cursor"))
{
cursor = j_object.get("cursor").toString();
}
else
{
cursor = "false";
}
String urlStr = urlStr_initial + "=" + cursor;
url = new URL(urlStr);
}while( !cursor.equalsIgnoreCase("false"));
if(list != null)
{
TextFile tf = new TextFile();
tf.writeToFile(list);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
private static String getQuery()
{
return "[{"
+ "\"name\": null,"
+ "\"id\": null,"
+ "\"type\":\"/people/person\","
+ "\"limit\": 500"
+ "}]";
}
You don't say what "large" is, but the API isn't designed for bulk downloads. You should be using the data dumps for that.
There's usually more detailed error message included with the HTTP response code. If, for example, it says 403 - Forbidden - API key required, it means you didn't include your API key (I don't see where you include it in your code). If it says 403 - Forbidden - quota exceeded it means you've exceeded your request quota (you can look on the API console to see how much quota you have remaining).