How to add test case when post a test case result - rally

The JsonObject addProperty cannot support to add another JsonObject.
The official test shown on below:
#Test
public void shouldConstructTheCorrectUrlWithExtraParam() {
JsonObject body = new JsonObject();
CreateRequest req = new CreateRequest("Defect", body);
req.addParam("foo", "Bar");
Assert.assertEquals(req.toUrl(), "/defect/create.js?foo=Bar&fetch=true");
}
What I need is ???:
public void shouldConstructTheCorrectUrlWithExtraParam() {
JsonObject body = new JsonObject();
body.add("testcase",???)
CreateRequest req = new CreateRequest("testcaseresult", body);
req.addParam("foo", "Bar");
Assert.assertEquals(req.toUrl(), "/defect/create.js?foo=Bar&fetch=true");
}

I did a mistake for adding other JsonObject, it's a ref instead a instance.
Works well code:
public void createTestCaseResult(JsonObject testCaseJsonObject) throws IOException, URISyntaxException {
log.println("createTestCaseResult...");
String testCaseRef = testCaseJsonObject.get("_ref").getAsString();
QueryRequest userRequest = new QueryRequest("user");
userRequest.setFetch(new Fetch("UserName", "Subscription", "DisplayName"));
userRequest.setQueryFilter(new QueryFilter("UserName", "=", "lu.han#technicolor.com"));
QueryResponse userQueryResponse = restApi.query(userRequest);
JsonArray userQueryResults = userQueryResponse.getResults();
JsonElement userQueryElement = userQueryResults.get(0);
JsonObject userQueryObject = userQueryElement.getAsJsonObject();
String userRef = userQueryObject.get("_ref").getAsString();
close();
getRestApi();
Date now = new Date();
String pattern = "yyyy-MM-dd'T'HH:mm:ssZ";
SimpleDateFormat format = new SimpleDateFormat(pattern);
JsonObject newResult = new JsonObject();
newResult.addProperty("Verdict", "Pass");
newResult.addProperty("Build", "2014.01.08.1234567");
newResult.addProperty("Tester", userRef);
newResult.addProperty("Date", format.format(now));
newResult.addProperty("CreationDate", format.format(now));
newResult.addProperty("TestCase", testCaseRef);
newResult.addProperty("Workspace", workspaceRef);
CreateRequest createRequest = new CreateRequest("testcaseresult", newResult);
CreateResponse createResponse = restApi.create(createRequest);
log.println("createTestCaseResult DONEļ¼š");
log.println(String.format("Created %s", createResponse.getObject().get("_ref").getAsString()));
}

Related

How to solve this circular dependency problem?

I have two interfaces for components that each requires functionality from the other one. One that generates Oauth tokens, and another one that gets secrets from a secret provider (Azure Key Vault).
The problem is that the Token Provider needs to obtain a secret value (a password) to make its HTTP call, and the Secret Provider class needs to get a Token in order to call Azure. Chicken and Egg problem.
From the other questions I've read, one suggestion is to create a third class/interface on which the original 2 depend, but I'm not sure how that would work here.
Any help and suggestions would be appreciated. Code for all relevant classes/interfaces is shown below.
public interface ISecretProvider
{
string GetSecret(string secretName);
}
public interface ITokenProvider
{
string GetKeyVaultToken();
}
public class OktaTokenProvider : ITokenProvider
{
ISecretProvider _secretProvider;
public string GetKeyVaultToken()
{
var tokenUrl = ConfigurationManager.AppSettings["KeyVault.Token.Url"];
var clientId = ConfigurationManager.AppSettings["KeyVault.Token.ClientId"];
var clientSecret = _secretProvider.GetSecret("ClientSecret");
var scope = ConfigurationManager.AppSettings["KeyVault.Scope"];
var token = GetToken(tokenUrl, clientId, clientSecret, scope);
return token;
}
private string GetToken(string tokenUrl, string clientId, string clientSecret, string scope)
{
var clientCredentials = $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}"))}";
string responseFromServer = string.Empty;
bool success = false;
int retryCount = 0;
while (!success)
{
try
{
var tokenWebRequest = (HttpWebRequest)WebRequest.Create(tokenUrl);
tokenWebRequest.Method = "POST";
tokenWebRequest.Headers.Add($"Authorization:{clientCredentials}");
tokenWebRequest.Headers.Add("Cache-control:no-cache");
tokenWebRequest.ContentType = "application/x-www-form-urlencoded";
using (var streamWriter = new StreamWriter(tokenWebRequest.GetRequestStream()))
{
streamWriter.Write($"grant_type=client_credentials&scope={scope}");
streamWriter.Flush();
streamWriter.Close();
}
using (WebResponse response = tokenWebRequest.GetResponse())
{
using (var dataStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
responseFromServer = reader.ReadToEnd();
reader.Close();
}
dataStream.Close();
}
response.Close();
response.Dispose();
}
success = true;
}
catch (Exception)
{
if (retryCount > 3)
{
throw;
}
else
{
retryCount++;
}
}
}
JToken token = JObject.Parse(responseFromServer);
var accessToken = $"Bearer {token.SelectToken("access_token").ToString()}";
return accessToken;
}
}
public class KeyVaultSecretProvider : ISecretProvider
{
ITokenProvider _tokenProvider;
public KeyVaultSecretProvider(ITokenProvider tokenProvider)
{
_tokenProvider = tokenProvider;
}
public string GetSecret(string secretName)
{
var KeyVaultUrl = ConfigurationManager.AppSettings[Constants.KEYVAULT_ENDPOINT];
var subscriptionKey = ConfigurationManager.AppSettings[Constants.KEYVAULT_SUBSCRIPTION_KEY];
string responseFromServer = "";
var requestedSecretUrl = $"{KeyVaultUrl}{secretName}";
var secretWebRequest = (HttpWebRequest)WebRequest.Create(requestedSecretUrl);
var accessToken = _tokenProvider.GetKeyVaultToken();
secretWebRequest.Method = "GET";
secretWebRequest.Headers.Add("authorization:" + accessToken);
secretWebRequest.Headers.Add("cache-control:no-cache");
secretWebRequest.Headers.Add("Ocp-Apim-Subscription-Key:" + subscriptionKey);
using (WebResponse response = secretWebRequest.GetResponse())
{
using (var dataStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
responseFromServer = reader.ReadToEnd();
reader.Close();
}
dataStream.Close();
}
response.Close();
response.Dispose();
}
JToken secret = JObject.Parse(responseFromServer);
var secretValue = secret.SelectToken("Secret").ToString();
return secretValue;
}
}
Have a single class implement both interfaces. The two responsibilities are inter-dependent, so put them together in one class. There is nothing wrong with this.

get data (single value) from ksoap to andorid through webservice

final String SOAP_ACTION = "http://tempuri.org/get_data2";
final String OPERATION_NAME = "get_data2";
final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";
final String SOAP_ADDRESS = "****";
final String req_no, req_date, bolnumber, container_no, current_loc, truck_no;
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE, OPERATION_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
try
{
httpTransport.call(SOAP_ACTION, envelope);
SoapObject resultsString = (SoapObject)envelope.getResponse();
Log.d("-----------------------", resultsString.getProperty("emp_name").toString());
tv.setText(resultsString.getPropertyCount());
}
catch (Exception exception)
{
exception.printStackTrace();
tv.setText(exception.toString());
}

How can I upload a file to rackspace using RESTSharp and .net 4.0?

Here is what i have so far and it's not working:
private void _send1(string file)
{
var client = new RestClient("https://identity.api.rackspacecloud.com/v2.0");
var request = new RestRequest("tokens", Method.POST);
request.RequestFormat = DataFormat.Json;
string test = "{\"auth\":{\"RAX-KSKEY:apiKeyCredentials\"{\"username\":\"";
test += UserName;
test += "\",\"apiKey\":\"";
test += MyToken;
test += "\"}}}";
request.AddBody(serText);
request.AddParameter("application/json", test, ParameterType.RequestBody);
RestResponse response = (RestResponse)client.Execute(request);
// Content = "{\"badRequest\":{\"code\":400,\"message\":\"java.lang.String cannot be cast to org.json.simple.JSONObject\"}}"
}
note: UserName and apiKey are valid RackSpace credentials :-)
Thanks
In advance
Try 2: ( found this on the web ) and it gives me a token... now what do I do with it?
private void _send2(string file)
{
Dictionary<string, object> dictAuth = new Dictionary<string, object>();
dictAuth.Add("RAX-KSKEY:apiKeyCredentials", new { username = UserName, apiKey = MyToken });
var auth = new
{
auth = dictAuth
};
RestClient client = new RestClient("https://identity.api.rackspacecloud.com");
RestSharp.RestRequest r = new RestRequest("/v2.0/tokens", Method.POST);
r.AddHeader("Content-Type", "application/json");
r.RequestFormat = DataFormat.Json;
r.AddBody(auth);
RestResponse response = (RestResponse)client.Execute(r);
// Content = "{\"access\":{\"token\":{\"id\":\"AACCvxjTOXA\",\"expires\":\"2016-04-09T21:12:10.316Z\",\"tenant\":{\"id\":\"572045\",\"name\...
}
moving just a bit further:
I have create a class that parses out the URL, tenantID and token from Step 2 above
This data is passed to the PostFile call:
private void PostFile(string url, string tenantID, string token, string file)
{
string fName = Path.GetFileName(file);
RestClient client = new RestClient(url);
string baseURL = string.Format("v1/{0}/Support/{1}", tenantID, fName);
RestRequest r = new RestRequest(baseURL, Method.POST);
r.AddHeader("Content-Type", "text/plain");
r.AddParameter("X-Auth-Token", token);
r.AddFile(fName, file);
RestResponse response = (RestResponse)client.Execute(r);
if( response.StatusCode == System.Net.HttpStatusCode.OK)
{
int x = 0;
}
}
Here is what finally worked:
bool bRetval = false;
string fName = Path.GetFileName(file);
RestClient client = new RestClient(url);
string baseURL = string.Format("/Support/{0}", fName);
RestRequest r = new RestRequest(baseURL, Method.PUT);
r.AddHeader("Content-Type", "text/plain");
r.AddHeader("X-Auth-Token", token);
r.AddFile(fName, file);
RestResponse response = (RestResponse)client.Execute(r);
See the above post for the supporting functions that lead up to this one
private bool PostFile(string url, string token, string file)
{
bool bRetval = false;
string fName = Path.GetFileName(file);
RestClient client = new RestClient(url);
string baseURL = string.Format("/Support/{0}", fName);
RestRequest r = new RestRequest(baseURL, Method.PUT);
r.AddHeader("Content-Type", "text/plain");
r.AddHeader("X-Auth-Token", token);
r.AddFile(fName, file);
RestResponse response = (RestResponse)client.Execute(r);
if ( response.StatusCode == System.Net.HttpStatusCode.Created)
{
bRetval = true;
}
return bRetval;
}

How to add screenshot into RallyDev using RAlly API

how to upload the screenshots into rally dev using the rally rest api. I am able to log defects. I need to log screenshots
Here is an example using Rally REST Api Tookit for Java that creates a defect and then creates an attachment on the defect:
public class CreateDefectAddAttachment{
public static void main(String[] args) throws URISyntaxException, IOException {
String host = "https://rally1.rallydev.com";
String apiKey = "_abc123";
String projectRef = "/project/12352608219";
String applicationName = "RestExample_createDefectAttachScreenshot";
RallyRestApi restApi = new RallyRestApi(new URI(host),apiKey);
restApi.setApplicationName(applicationName);
//Read User
QueryRequest userRequest = new QueryRequest("User");
userRequest.setQueryFilter(new QueryFilter("UserName", "=", "user#company.com"));
QueryResponse userQueryResponse = restApi.query(userRequest);
JsonArray userQueryResults = userQueryResponse.getResults();
JsonElement userQueryElement = userQueryResults.get(0);
JsonObject userQueryObject = userQueryElement.getAsJsonObject();
String userRef = userQueryObject.get("_ref").getAsString();
try {
for (int i=0; i<1; i++) {
//Create a defect
JsonObject newDefect = new JsonObject();
newDefect.addProperty("Name", "bug1234");
newDefect.addProperty("Project", projectRef);
CreateRequest createRequest = new CreateRequest("defect", newDefect);
CreateResponse createResponse = restApi.create(createRequest);
if (createResponse.wasSuccessful()) {
System.out.println(String.format("Created %s", createResponse.getObject().get("_ref").getAsString()));
//Read defect
String ref = Ref.getRelativeRef(createResponse.getObject().get("_ref").getAsString());
System.out.println(String.format("\nReading Defect %s...", ref));
String imageFilePath = "C:/";
String imageFileName = "pic.png";
String fullImageFile = imageFilePath + imageFileName;
String imageBase64String;
long attachmentSize;
// Open file
RandomAccessFile myImageFileHandle = new RandomAccessFile(fullImageFile, "r");
try {
long longLength = myImageFileHandle.length();
long maxLength = 5000000;
if (longLength >= maxLength) throw new IOException("File size >= 5 MB Upper limit for Rally.");
int fileLength = (int) longLength;
// Read file and return data
byte[] fileBytes = new byte[fileLength];
myImageFileHandle.readFully(fileBytes);
imageBase64String = Base64.encodeBase64String(fileBytes);
attachmentSize = fileLength;
// First create AttachmentContent from image string
JsonObject myAttachmentContent = new JsonObject();
myAttachmentContent.addProperty("Content", imageBase64String);
CreateRequest attachmentContentCreateRequest = new CreateRequest("AttachmentContent", myAttachmentContent);
CreateResponse attachmentContentResponse = restApi.create(attachmentContentCreateRequest);
String myAttachmentContentRef = attachmentContentResponse.getObject().get("_ref").getAsString();
System.out.println("Attachment Content created: " + myAttachmentContentRef);
//Create the Attachment
JsonObject myAttachment = new JsonObject();
myAttachment.addProperty("Artifact", ref);
myAttachment.addProperty("Content", myAttachmentContentRef);
myAttachment.addProperty("Name", "AttachmentFromREST.png");
myAttachment.addProperty("Description", "Attachment From REST");
myAttachment.addProperty("ContentType","image/png");
myAttachment.addProperty("Size", attachmentSize);
myAttachment.addProperty("User", userRef);
CreateRequest attachmentCreateRequest = new CreateRequest("Attachment", myAttachment);
CreateResponse attachmentResponse = restApi.create(attachmentCreateRequest);
String myAttachmentRef = attachmentResponse.getObject().get("_ref").getAsString();
System.out.println("Attachment created: " + myAttachmentRef);
if (attachmentResponse.wasSuccessful()) {
System.out.println("Successfully created Attachment");
} else {
String[] attachmentContentErrors;
attachmentContentErrors = attachmentResponse.getErrors();
System.out.println("Error occurred creating Attachment: ");
for (int j=0; j<attachmentContentErrors.length;j++) {
System.out.println(attachmentContentErrors[j]);
}
}
}catch (Exception e) {
System.out.println("Exception occurred while attempting to create Content and/or Attachment: ");
e.printStackTrace();
}
} else {
String[] createErrors;
createErrors = createResponse.getErrors();
System.out.println("Error occurred creating a defect: ");
for (int j=0; i<createErrors.length;j++) {
System.out.println(createErrors[j]);
}
}
}
} finally {
//Release all resources
restApi.close();
}
}
}

Converting a JSON object to an equivalent in JAVA

I am massively stuck with converting a PHP server request into an equivalent Java Request. This is the code that contains the JSON object that I need to replicate in JAVA and send from an Android device:
$(".unableprocess").click(function() {
if (!confirm("Confirm not able to process...!")) {
return false;
} else {
var item_id = $(this).attr('data-id');
var table_id = $(this).attr('table-id');
var data = {
BookOrders: {
item_id: item_id,
table_id: table_id
}
};
$.ajax({
url: //MY URL HERE ,
type: "POST",
data: data,
success: function(evt, responseText) {
location.reload();
}
});
}
});
And here is my Java class that attempts to perform the same functionality. The class extends AsyncTask and all network interactions occur in the doInBackground() method. Here is my code:
#Override
protected Boolean doInBackground(String... arg0) {
try{
HashMap<String, String> hashMap = new HashMap<String,String>();
JSONObject jsonObject = new JSONObject();
int statusCode;
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(tableMateCannotProcessURL);
// JSON object creation begins here:
jsonObject.accumulate("item_id",this.itemId);
jsonObject.accumulate("table_id",this.tableId);
JSONObject jObject = new JSONObject();
jObject.accumulate("BookOrders", jsonObject);
// JSON object ends here
Log.v("ATOMIC BLAST",jObject.toString());
String json = jObject.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
HttpResponse response = client.execute(httpPost);
statusCode = response.getStatusLine().getStatusCode();
Integer statusCodeInt = new Integer(statusCode);
Log.v("HTTPResponse",statusCodeInt.toString());
String result= "";
StringBuilder builder = new StringBuilder();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
result = builder.toString();
}
else {
Log.e("==>", "Failed to download file");
}
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
The JSON object that I created looks like this after printing it out to the console:
{"BookOrders":{"table_id":"1","item_id":"2"}}
After POSTing this object to the server I do not get the expected response. What is the proper method for converting the JSON object into an equivalent JSON object in JAVA? Any guidance, direction or a solution would be most appreciated.
Update php to version 5.4 helped me.
In this version json_encode($x, JSON_PRETTY_PRINT) works just as needed.
Your JSON seems to be correct but it's an Object in an Object.
JSONObject json = new JSONObject(yourdata);
JSONObject jsonTable = new JSONObject(json.getString("BookOrders"));
Log.d("JsonDebug", "json:" + jsonTable.toString());
If you are not sure if you have a JSONObject or an Array you can validate it by using
String data = "{ ... }";
Object json = new JSONTokener(data).nextValue();
if (json instanceof JSONObject)
//you have an object
else if (json instanceof JSONArray)
//you have an array