unable to print test cases in a test set using rallyapi - rally

My idea was to update testcaseresults present in a test set.but i am not able to get test cases present in a testset.
i was triyng to get into test set and get the test case where i can query for each of the test
RallyRestApi restApi = new RallyRestApi(new URI("https://rally1.rallydev.com"), "username", "pass");
restApi.setApplicationName("CrudExample");
QueryRequest testSetRequest = new QueryRequest("TestSet");
testSetRequest.setFetch(new Fetch(new String[]{"Name","TestCases","FormattedID"}));
testSetRequest.setQueryFilter(new QueryFilter("FormattedID", "=", "TS346"));
QueryResponse testSetQueryResponse = restApi.query(testSetRequest);
if(testSetQueryResponse.wasSuccessful()){
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").getAsJsonObject().get("_ref"));
// int numberOfTestCases = testSetJsonObject.get("TestCases").getAsJsonArray().size();
GetRequest getRequest = new GetRequest("https://rally1.rallydev.com/slm/webservice/v2.0/TestSet/15150807/TestCases");
GetResponse getResponse = restApi.get(getRequest);
JsonObject obj = getResponse.getObject();
System.out.println(obj.getAsString());
int numberOfTestCases = testSetJsonObject.get("TestCases").getAsJsonObject().get("Count").getAsInt();
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"));
}
}
}
}
else {
String[] createErrors;
createErrors = testSetQueryResponse.getErrors();
System.out.println("Error occurred creating Test Case: ");
for (int i=0; i<createErrors.length;i++) {
System.out.println(createErrors[i]);
}
}
output:
Successful: true
Size: 1
Name: "pre-acceptance automated regression" ref:rally1.rallydev.com/slm/webservice/v2.0/testset/15150807667
Test Cases: "rally1.rallydev.com/slm/webservice/v2.0/TestSet/15150807667/TestCases

Instead of this:
int numberOfTestCases = testSetJsonObject.get("TestCases").getAsJsonObject().get("Count").getAsInt();
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"));
}
Use this:
if(numberOfTestCases>0){
QueryRequest testCaseRequest = new QueryRequest(testSetJsonObject.getAsJsonObject("TestCases"));
testCaseRequest.setFetch(new Fetch(new String[] {"Name", "Results", "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());
}
}

Related

Saving ArrayList<Uri> in SharedPreferences and retrieving

I am trying to save multiple images into Uri List in SharedPreferences and retrieving them on another activity. I have code here. The error occurs that no adapter attached.
saving :
JSONArray a = new JSONArray();
for (int i = 0; i < uriList.size(); i++) {
a.put(uriList.get(i));
}
String save_form_image = "{\"uri\":\""+a+"\"}";
pref.setStringImage(getApplicationContext(),getTime,save_form_image);
retrieving :
pref = new PreferenceManager();
rv = (RecyclerView) findViewById(R.id.review_image_rv);
uriList = new ArrayList<Uri>();
manager = new LinearLayoutManager(Review.this, manager.HORIZONTAL, false);
rv.setLayoutManager(manager);
rv.setAdapter(image_adapter);
image_adapter = new MultiImageAdapter(uriList,Review.this);
prefs = getSharedPreferences("uri",MODE_PRIVATE);
Collection<?> col_val = prefs.getAll().values();
Iterator<?> it_val = col_val.iterator();
Collection<?> col_key = prefs.getAll().keySet();
Iterator<?> it_key = col_key.iterator();
while (it_val.hasNext() && it_key.hasNext()) {
String value = (String) it_val.next();
String key = (String) it_key.next();
try {
JSONObject jsonObject = new JSONObject(value);
String json = jsonObject.getString("uri");
JSONArray jsonArray = new JSONArray(json);
for(int i = 0; i < jsonArray.length(); i++) {
String a = (String) jsonArray.get(i);
uri = Uri.parse(a);
uriList.add(uri);
image_adapter.addItem(key,uriList);
}
Toast.makeText(getApplicationContext(),"loaded",Toast.LENGTH_SHORT).show();
} catch (JSONException e) {}
image_adapter.notifyDataSetChanged();
}
System.out.println(image_adapter.getItemCount());

Is it possible to return an array of dictionaries?

I wrote a function that will return a single sql record as a dictionary. Is it possible to return an array of dictionaries so I can return multiple records in this way?
public static async Task<Dictionary<string, string>> SQLMultiRecordToDictionary(string TableName, string SearchField, string SearchValue)
{
Dictionary<string, string> QueryResult = new Dictionary<string, string>();
// is TableName sane
if (!IsTextSane(TableName)) { return QueryResult; }
//
await using (var connection = new SqliteConnection("Data Source=" + dbFullPathName))
{
connection.Open();
SqliteCommand sqlcmd = connection.CreateCommand();
sqlcmd.CommandText = "SELECT * FROM " + TableName + " WHERE " + SearchField + "=#SearchValue";
sqlcmd.Parameters.AddWithValue("#SearchValue", SearchValue);
SqliteDataReader sqlreader = sqlcmd.ExecuteReader();
// generate dictionary keys with blank values
// this prevents key not existing issues when no record is returned
// i prefer no/blank values in the keys when no record returned for this project
for (int i = 0; i < sqlreader.FieldCount; i++)
{
QueryResult.Add(sqlreader.GetName(i), ""); // blank value
}
// add the values to the keys
while (sqlreader.Read())
{
for (int i = 0; i <= sqlreader.FieldCount - 1; i++)
{
QueryResult[sqlreader.GetName(i)] = sqlreader.GetString(i);
}
}
return QueryResult;
}
}
The working end result thanks to Tisa:
public static async Task<List<Dictionary<string, string>>> SQLMultiRecordToDictionaryList(string TableName, string SearchField, string SearchValue)
{
List<Dictionary<string, string>> QueryResult = new List<Dictionary<string, string>>();
Dictionary<string, string> SQLRecord = new Dictionary<string, string>();
//
// is TableName sane, if not return nothing
if (!IsTextSane(TableName)) { return QueryResult; }
//
await using (var connection = new SqliteConnection("Data Source=" + dbFullPathName))
{
connection.Open();
SqliteCommand sqlcmd = connection.CreateCommand();
sqlcmd.CommandText = "SELECT * FROM " + TableName + " WHERE " + SearchField + "=#SearchValue";
sqlcmd.Parameters.AddWithValue("#SearchValue", SearchValue);
SqliteDataReader sqlreader = sqlcmd.ExecuteReader();
// generate dictionary keys with blank values if no rows
// this prevents key not existing issues when no record is returned
// i prefer no/blank values in the keys when no record returned for this project
if (!sqlreader.HasRows)
{
for (int i = 0; i < sqlreader.FieldCount; i++)
{
SQLRecord.Add(sqlreader.GetName(i), ""); // blank value
}
QueryResult.Add(SQLRecord);
}
//
// add the values to the keys if there are rows (this doesn't run if no rows returned)
while (sqlreader.Read())
{
SQLRecord = new Dictionary<string, string>();
for (int i = 0; i <= sqlreader.FieldCount - 1; i++)
{
SQLRecord.Add(sqlreader.GetName(i), sqlreader.GetString(i));
}
QueryResult.Add(SQLRecord);
}
return QueryResult;
}
}

Null pointer exception on Processing (ldrValues)

My code involves both Processing and Arduino. 5 different photocells are triggering 5 different sounds. My sound files play only when the ldrvalue is above the threshold.
The Null Pointer Exception is highlighted on this line
for (int i = 0; i < ldrValues.length; i++) {
I am not sure which part of my code should be changed so that I can run it.
import processing.serial.*;
import processing.sound.*;
SoundFile[] soundFiles = new SoundFile[5];
Serial myPort; // Create object from Serial class
int[] ldrValues;
int[] thresholds = {440, 490, 330, 260, 450};
int i = 0;
boolean[] states = {false, false, false, false, false};
void setup() {
size(200, 200);
println((Object[])Serial.list());
String portName = Serial.list()[3];
myPort = new Serial(this, portName, 9600);
soundFiles[0] = new SoundFile(this, "1.mp3");
soundFiles[1] = new SoundFile(this, "2.mp3");
soundFiles[2] = new SoundFile(this, "3.mp3");
soundFiles[3] = new SoundFile(this, "4.mp3");
soundFiles[4] = new SoundFile(this, "5.mp3");
}
void draw()
{
background(255);
//serial loop
while (myPort.available() > 0) {
String myString = myPort.readStringUntil(10);
if (myString != null) {
//println(myString);
ldrValues = int(split(myString.trim(), ','));
//println(ldrValues);
}
}
for (int i = 0; i < ldrValues.length; i++) {
println(states[i]);
println(ldrValues[i]);
if (ldrValues[i] > thresholds[i] && !states[i]) {
println("sensor " + i + " is activated");
soundFiles[i].play();
states[i] = true;
}
if (ldrValues[i] < thresholds[i]) {
println("sensor " + i + " is NOT activated");
soundFiles[i].stop();
states[i] = false;
}
}
}
You're approach is shall we say optimistic ? :)
It's always assuming there was a message from Serial, always formatted the right way so it could be parsed and there were absolutely 0 issues buffering data (incomplete strings, etc.))
The simplest thing you could do is check if the parsing was successful, otherwise the ldrValues array would still be null:
void draw()
{
background(255);
//serial loop
while (myPort.available() > 0) {
String myString = myPort.readStringUntil(10);
if (myString != null) {
//println(myString);
ldrValues = int(split(myString.trim(), ','));
//println(ldrValues);
}
}
// double check parsing int values from the string was successfully as well, not just buffering the string
if(ldrValues != null){
for (int i = 0; i < ldrValues.length; i++) {
println(states[i]);
println(ldrValues[i]);
if (ldrValues[i] > thresholds[i] && !states[i]) {
println("sensor " + i + " is activated");
soundFiles[i].play();
states[i] = true;
}
if (ldrValues[i] < thresholds[i]) {
println("sensor " + i + " is NOT activated");
soundFiles[i].stop();
states[i] = false;
}
}
}else{
// print a helpful debugging message otherwise
println("error parsing ldrValues from string: " + myString);
}
}
(Didn't know you could parse a int[] with int(): nice!)

How to store a webtable in arraylist then verify the data in selenium webdriver

I want to store Rows and Column of web table into array list, then will verify the data. I am available to print the rows but how I will store the rows.
public void verifyTable() {
String Test = driver.findElement(loggedinas).getText();
boolean isDue = false;
isDue = UtilClass.isElementPresent(driver, TableContent);
if (isDue) {
if (isDue = driver.findElement(TableContent).getText() != null)
;
System.out.println("Action Required = " + isDue);
WebElement table_element = driver.findElement(Table);
List<WebElement> tr_collection = table_element
.findElements(TableRow);
System.out.println("Number Of Due = " + tr_collection.size());
int row_num, col_num;
row_num = 1;
for (WebElement trElement : tr_collection) {
List<WebElement> td_collection = trElement.findElements(By.xpath("td"));
System.out.println("--NUMBER OF COLUMNS = "
+ td_collection.size() + "--");
col_num = 1;
for (WebElement tdElement : td_collection) {
// System.out.println("Pending # "+row_num+", col # "+col_num+
// "text="+tdElement.getText());
System.out.printf(" # " + tdElement.getText(), " ID "
+ tdElement.getText());
col_num++;
}
row_num++;
}
Thank you!
I had done something similar, please check this function bellow, this will give you an idea
public void manageUserDataGrid(WebDriver driver){
WebElement table = driver.findElement(By.xpath("//*[#id='ReportTable']"));
List<WebElement> rows = table.findElements(By.tagName("tr"));
List<WebElement> column = table.findElements(By.tagName("td"));
List<String> value = new ArrayList<String>();
System.out.println(rows.size());
for (int j=0; j<column.size(); j++){
System.out.println(column.get(j).getText());
value.add(column.get(j).getText());
}
if (value.contains("coadminss")){
System.out.println("Value found");
}
else{
System.out.println("Not Found");
}
}

CloudStack: Unable to verify user credentials and/or request signature

I am working on CloudStack API now and I have the problem about making the API request. I always got "{ "listtemplatesresponse" : {"errorcode":401,"errortext":"unable to verify user credentials and/or request signature"} }" even though I change the parameter.
This error occurs in some commands that require the parameter and this is the command that I use:
command=listTemplates&templatefilter=featured
I don't know what I did wrong since it works with others. Here is the code I use to make the API request:
try {
String encodedApiKey = URLEncoder.encode(apiKey.toLowerCase(), "UTF-8");
ArrayList<String> sortedParams = new ArrayList<String>();
sortedParams.add("apikey="+encodedApiKey);
StringTokenizer st = new StringTokenizer(apiUrl, "&");
while (st.hasMoreTokens()) {
String paramValue = st.nextToken().toLowerCase();
String param = paramValue.substring(0, paramValue.indexOf("="));
String value = URLEncoder.encode(paramValue.substring(paramValue.indexOf("=")+1, paramValue.length()), "UTF-8");
sortedParams.add(param + "=" + value);
}
Collections.sort(sortedParams);
System.out.println("Sorted Parameters: " + sortedParams);
String sortedUrl = null;
boolean first = true;
for (String param : sortedParams) {
if (first) {
sortedUrl = param;
first = false;
} else {
sortedUrl = sortedUrl + "&" + param;
}
}
sortedUrl += "&response=json";
System.out.println("sorted URL : " + sortedUrl);
String encodedSignature = signRequest(sortedUrl, secretKey);
String finalUrl = host + "?" + apiUrl + "&response=json&apiKey=" + apiKey + "&signature=" + encodedSignature;
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(finalUrl);
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
System.out.println("str: "+str);
result = str.toString();
System.out.println("result: "+str);
}
else
System.out.println("Error response!!");
} catch (Throwable t) {
System.out.println(t);
}
And this is signRequest function:
public static String signRequest(String request, String key) {
try {
Mac mac = Mac.getInstance("HmacSHA1");
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
mac.init(keySpec);
mac.update(request.getBytes());
byte[] encryptedBytes = mac.doFinal();
return URLEncoder.encode(Base64.encodeBytes(encryptedBytes), "UTF-8");
} catch (Exception ex) {
System.out.println(ex);
}
return null;
}
Please feel free to ask me if you need more information. All comments and advice are welcome!
Have you tried sorting after you've added "&response=json" to the list of parameters?
E.g.
try {
String encodedApiKey = URLEncoder.encode(apiKey.toLowerCase(), "UTF-8");
ArrayList<String> sortedParams = new ArrayList<String>();
sortedParams.add("apikey="+encodedApiKey);
sortedParams.add("response=json");
StringTokenizer st = new StringTokenizer(apiUrl, "&");
while (st.hasMoreTokens()) {
String paramValue = st.nextToken().toLowerCase();
String param = paramValue.substring(0, paramValue.indexOf("="));
String value = URLEncoder.encode(paramValue.substring(paramValue.indexOf("=")+1, paramValue.length()), "UTF-8");
sortedParams.add(param + "=" + value);
}
Collections.sort(sortedParams);
System.out.println("Sorted Parameters: " + sortedParams);
String sortedUrl = null;
boolean first = true;
for (String param : sortedParams) {
if (first) {
sortedUrl = param;
first = false;
} else {
sortedUrl = sortedUrl + "&" + param;
}
}
System.out.println("sorted URL : " + sortedUrl);
String encodedSignature = signRequest(sortedUrl, secretKey);
String finalUrl = host + "?" + apiUrl + "&response=json&apiKey=" + apiKey + "&signature=" + encodedSignature;
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(finalUrl);
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
System.out.println("str: "+str);
result = str.toString();
System.out.println("result: "+str);
}
else
System.out.println("Error response!!");
} catch (Throwable t) {
System.out.println(t);
}
Your API Key and Response parameters need to be part of the sorted Url used when signing, which they appear to be.
try changing
return URLEncoder.encode(Base64.encodeBytes(encryptedBytes), "UTF-8");
to
return URLEncoder.encode(Base64.encodeAsString(encryptedBytes), "UTF-8");