How to add screenshot into RallyDev using RAlly API - rally

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();
}
}
}

Related

How to convert MailAttachment to MimeKit Attachment

We have to rework how we're sending emails since we are using Amazon SES. In the past, we were using smtp but can't do that in this case. The class that needs updated has taken in a MailMessage object and used smtp to send it. So I'm trying to rework the method to be able to continue to accept the MailMessage object and convert it to a MimeKit MimeMessage. For the most part it's working fine except when it comes to attachments. In the code I have, the attachment gets added and sent, however, when trying to open it appears it's corrupted or something. In my test case I attached a csv file. I could not open it in excel after receiving the email.
public class EmailAbstraction
{
public virtual void Send(MailMessage mailMessage)
{
sendMessage(mailMessage);
}
private static void sendMessage(MailMessage mailMessage)
{
using (var client = new AmazonSimpleEmailServiceClient(AwsConstants.SESAWSKey, AwsConstants.SESAWSSecret, AwsConstants.RegionEndpoint))
{
foreach (var to in mailMessage.To)
{
using (var messageStream = new MemoryStream())
{
var newMessage = new MimeMessage();
var builder = new BodyBuilder
{
HtmlBody = mailMessage.Body
};
newMessage.From.Add(mailMessage.From == null
? new MailboxAddress(EmailConstants.DefaultFromEmailDisplayName, EmailConstants.DefaultFromEmailAddress)
: new MailboxAddress(mailMessage.From.Address));
newMessage.To.Add(new MailboxAddress(to.DisplayName, to.Address));
newMessage.Subject = mailMessage.Subject;
foreach (var attachment in mailMessage.Attachments)
{
builder.Attachments.Add(attachment.Name, attachment.ContentStream);
}
newMessage.Body = builder.ToMessageBody();
newMessage.WriteTo(messageStream);
var request = new SendRawEmailRequest
{
RawMessage = new RawMessage { Data = messageStream }
};
client.SendRawEmail(request);
}
}
}
}
}
And in my test app, I have this.
internal class Program
{
private static void Main(string[] args)
{
var s = GetFileStream();
var m = new MailMessage();
var sender = new MailAddress("info#ourwebsite.com", "info");
m.From = sender;
m.Sender = sender;
m.Body = "test email";
m.Subject = "test subject";
m.To.Add(myemail);
m.Attachments.Add(new Attachment(s, "test-file.csv"));
new EmailAbstraction().Send(m);
}
private static MemoryStream GetFileStream()
{
var stream = new MemoryStream();
var fileStream = File.Open(#"C:\Users\dev\Desktop\test-file.csv", FileMode.Open);
fileStream.CopyTo(stream);
fileStream.Close();
return stream;
}
}
This is just copied from the MimeKit source code:
static MimePart GetMimePart (System.Net.Mail.AttachmentBase item)
{
var mimeType = item.ContentType.ToString ();
var contentType = ContentType.Parse (mimeType);
var attachment = item as System.Net.Mail.Attachment;
MimePart part;
if (contentType.MediaType.Equals ("text", StringComparison.OrdinalIgnoreCase))
part = new TextPart (contentType);
else
part = new MimePart (contentType);
if (attachment != null) {
var disposition = attachment.ContentDisposition.ToString ();
part.ContentDisposition = ContentDisposition.Parse (disposition);
}
switch (item.TransferEncoding) {
case System.Net.Mime.TransferEncoding.QuotedPrintable:
part.ContentTransferEncoding = ContentEncoding.QuotedPrintable;
break;
case System.Net.Mime.TransferEncoding.Base64:
part.ContentTransferEncoding = ContentEncoding.Base64;
break;
case System.Net.Mime.TransferEncoding.SevenBit:
part.ContentTransferEncoding = ContentEncoding.SevenBit;
break;
//case System.Net.Mime.TransferEncoding.EightBit:
// part.ContentTransferEncoding = ContentEncoding.EightBit;
// break;
}
if (item.ContentId != null)
part.ContentId = item.ContentId;
var stream = new MemoryStream ();
item.ContentStream.CopyTo (stream);
stream.Position = 0;
part.Content = new MimeContent (stream);
return part;
}

How to encrypt payload file streamingly via WSO2 ESB

I have to implement a scenario by using WSO2 ESB, as encrypting the binary payload streamingly while response to the client side (I assume the content-type in the case is Application/Octet-Stream), below is some details by my thought:
An Endpoint like "http://myhost/backend/" which provides business functionality;
A proxy which pass messages through the endpoint;
I attempt to write an OutSequence to check the Content-type: if the Content-Type matches Application/Octet-Stream, invoke my customized class mediator to encrypt the fileStream Streamingly and response.
I have no idea on how to write the class mediator to make it implemented? How could I get/read the file stream from the message as well as how to put the outputStream back to the response while I could only see mc.getEnvelope().getBody() in mediation method? Below is my current mediator which doesn't work.
public boolean mediate(MessageContext mc) {
org.apache.axis2.context.MessageContext amc = ((Axis2MessageContext) mc).getAxis2MessageContext();
try {
String contentID = amc.getAttachmentMap().getAllContentIDs()[0];
DataHandler dh = amc.getAttachment(contentID);
dh.getDataSource().getName();
InputStream is = null;
try {
is = dh.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println("client read:" + line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
Many thanks if anybody with experience would kindly help.
Pasted my current solution for anyone else who confronts similar issue.
In the mediator, I read the file content from response stream via OMText.InputStream and use net.lingala.zip4j package to write a zip file(in memory) with the raw file encrypted; Finally I write the zip file content as ByteArray back to the OMElement of the soap message.
public boolean mediate(MessageContext mc) {
System.out.println("========================Mediator log start================================");
org.apache.axis2.context.MessageContext amc = ((Axis2MessageContext) mc).getAxis2MessageContext();
try {
#SuppressWarnings("unchecked")
Map<String, String> responseHeaders = (Map<String, String>) amc.getProperty("TRANSPORT_HEADERS");
String rawFileName = "";
String[] contentDisps = responseHeaders.get("Content-Disposition").split(";");
for (String item : contentDisps) {
System.out.println("item::" + item);
if (item.trim().startsWith(CONTENT_DISPOSITION_FILENAME)) {
rawFileName = item.substring(item.indexOf("\"") + 1, item.length() - 1);
break;
}
}
responseHeaders.put(
"Content-Disposition",
responseHeaders.get("Content-Disposition").replace(rawFileName,
rawFileName.substring(0, rawFileName.lastIndexOf(".")) + ".myzip"));
OMElement binaryPayload =
amc.getEnvelope().getBody()
.getFirstChildWithName(new QName("http://ws.apache.org/commons/ns/payload", "binary"));
OMText binaryNode = (OMText) binaryPayload.getFirstOMChild();
DataHandler dataHandler = (DataHandler) binaryNode.getDataHandler();
InputStream is = dataHandler.getInputStream();
ByteArrayOutputStream responseOutputStream = new ByteArrayOutputStream();
ZipOutputStream zipOutputStream = getZipOutputStreamInstance(responseOutputStream, rawFileName);
// write to zipOutputStream
byte data[] = new byte[BUFFER_SIZE];
int count;
while ((count = is.read(data, 0, BUFFER_SIZE)) != -1) {
zipOutputStream.write(data, 0, count);
zipOutputStream.flush();
}
zipOutputStream.closeEntry();
zipOutputStream.finish();
InputStream in = new ByteArrayInputStream(responseOutputStream.toByteArray());
DataHandler zipDataHandler = new DataHandler(new StreamingOnRequestDataSource(in));
OMFactory factory = OMAbstractFactory.getOMFactory();
OMText zipData = factory.createOMText(zipDataHandler, true);
zipData.setBinary(true);
binaryPayload.getFirstOMChild().detach();
binaryPayload.addChild(zipData);
amc.setProperty("TRANSPORT_HEADERS", responseHeaders);
System.out.println("========================Mediator end==================================");
} catch (Exception ex) {
System.out.println("exception found here:");
ex.printStackTrace();
}
return true;
}

how to use paging in new graph facebook v4

I have tried the code below but I am getting an error.How can I use paging in v4 facebook after/within login?
// Callback registration
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request2 = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
JSONObject uu= response.getJSONObject();
if (uu!=null){
Log.w(TAG, "respomse: " + response.toString());
}
GraphRequest nextPageRequest = response.getRequestForPagedResults(GraphResponse.PagingDirection.NEXT);
if (nextPageRequest != null) {
nextPageRequest.setCallback(new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
}
});

 
 
 nextPageRequest.executeBatchAsync(
}
}
});
Bundle parameters2 = new Bundle();
parameters2.putString("fields", "likes");
parameters2.putString("limit", "999");
request2.setParameters(parameters2);
request2.executeAsync();
});
}
}
I use this code within my User class. Every time a new user signs up using Facebook, this gets executed by calling get_user_data() within the User constructor.
For the below example to work for you too, you'll need an access token with the following permissions:
user_friends
email
Constants:
private ArrayList<HashMap> user_fb_friends;
private final String FIELDS = "id,first_name,last_name,name,gender,locale,timezone,updated_time,email,link,picture,friends{id,first_name,last_name,name,gender,updated_time,link,picture}";
private final String USER_FB_ID_TAG = "id";
private final String F_NAME_TAG = "first_name";
private final String L_NAME_TAG = "last_name";
private final String FULL_NAME_TAG = "name";
private final String GENDER_TAG = "gender";
private final String LOCALE_TAG = "locale";
private final String TIMEZONE_TAG = "timezone";
private final String UPDATED_TIME_TAG = "updated_time";
private final String EMAIL_TAG = "email";
private final String LINK_TAG = "link";
private final String PICTURE_TAG = "picture";
private final String DATA_TAG = "data";
private final String IS_SILHOUETTE_TAG = "is_silhouette";
private final String URL_TAG = "url";
private final String FRIENDS_TAG = "friends";
private final String PAGING_TAG = "paging";
private final String NEXT_TAG = "next";
private final String SUMMARY_TAG = "summary";
private final String TOTAL_COUNT_TAG = "total_count";
Actual code:
(the following code includes local setters)
private void get_user_data(){
GraphRequest request = GraphRequest.newMeRequest(
Signup_fragment.mAccessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
JSONObject json = response.getJSONObject();
if(json != null){
try {
user_fb_friends = new ArrayList<>();
/*
* Start parsing the JSON
* 1. Pars the user personal details and save them on new User class
*/
setUser_fb_id(json.getString(USER_FB_ID_TAG));
setF_name(json.getString(F_NAME_TAG));
setL_name(json.getString(L_NAME_TAG));
setFull_name(json.getString(FULL_NAME_TAG));
setGender(json.getString(GENDER_TAG));
setLocale(json.getString(LOCALE_TAG));
setTimezone(json.getInt(TIMEZONE_TAG));
setUpdated_time((Date) json.get(UPDATED_TIME_TAG));
setEmail(json.getString(EMAIL_TAG));
setFb_profile_link(json.getString(LINK_TAG));
Utils.log("User prsonal data was collected (" + getFull_name() + ")");
JSONObject pic_wrapper = json.getJSONObject(PICTURE_TAG);
JSONObject pic_data = pic_wrapper.getJSONObject(DATA_TAG);
if(!pic_data.getBoolean(IS_SILHOUETTE_TAG)){
setFb_profile_pic_link(pic_data.getString(URL_TAG));
}
/*
* 2. Go over the jsonArry of friends, pars and save each friend
* in a HashMap object and store it in user_fb_friends array
*/
JSONObject friends_wrapper = json.getJSONObject(FRIENDS_TAG);
JSONArray friends_json_array = friends_wrapper.getJSONArray(DATA_TAG);
if(friends_json_array.length() > 0){
for (int i = 0; i < friends_json_array.length(); i++) {
HashMap<String, String> friend_hashmap = new HashMap<String, String>();
JSONObject friend_json = friends_json_array.getJSONObject(i);
friend_hashmap.put(USER_FB_ID_TAG, friend_json.getString(USER_FB_ID_TAG));
friend_hashmap.put(F_NAME_TAG, friend_json.getString(F_NAME_TAG));
friend_hashmap.put(L_NAME_TAG, friend_json.getString(L_NAME_TAG));
friend_hashmap.put(FULL_NAME_TAG, friend_json.getString(FULL_NAME_TAG));
friend_hashmap.put(GENDER_TAG, friend_json.getString(GENDER_TAG));
friend_hashmap.put(UPDATED_TIME_TAG, friend_json.getString(UPDATED_TIME_TAG));
friend_hashmap.put(LINK_TAG, friend_json.getString(LINK_TAG));
JSONObject friend_pic_wrapper = json.getJSONObject(PICTURE_TAG);
JSONObject friend_pic_data = friend_pic_wrapper.getJSONObject(DATA_TAG);
if(!friend_pic_data.getBoolean(IS_SILHOUETTE_TAG)){
friend_hashmap.put(URL_TAG, friend_pic_data.getString(URL_TAG));
}
user_fb_friends.add(friend_hashmap);
Utils.log("A friend was added to user_fb_friends (" + i + ")");
}
/*
* 3. Get the URL for the next "friends" JSONObject and send
* a GET request
*/
JSONObject paging_wrapper = json.getJSONObject(PAGING_TAG);
String next_friends_json_url = null;
if(paging_wrapper.getString(NEXT_TAG) != null){
next_friends_json_url = paging_wrapper.getString(NEXT_TAG);
}
JSONObject summary_wrapper = json.getJSONObject(SUMMARY_TAG);
int total_friends_count = summary_wrapper.getInt(TOTAL_COUNT_TAG);
if(next_friends_json_url != null){
/*
* Send a GET request for the next JSONObject
*/
get_paging_data(response);
}
} else {
Utils.log("friends_json_array == null");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", FIELDS);
request.setParameters(parameters);
request.executeAsync();
}
private void get_paging_data(GraphResponse response){
GraphRequest nextRequest = response.getRequestForPagedResults(GraphResponse.PagingDirection.NEXT);
Utils.log("get_paging_data was called");
nextRequest.setCallback(new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
JSONObject json = response.getJSONObject();
if (json != null) {
try {
JSONArray friends_json_array = json.getJSONArray(DATA_TAG);
for (int i = 0; i < friends_json_array.length(); i++) {
HashMap<String, String> friend_hashmap = new HashMap<String, String>();
JSONObject friend_json = friends_json_array.getJSONObject(i);
friend_hashmap.put(USER_FB_ID_TAG, friend_json.getString(USER_FB_ID_TAG));
friend_hashmap.put(F_NAME_TAG, friend_json.getString(F_NAME_TAG));
friend_hashmap.put(L_NAME_TAG, friend_json.getString(L_NAME_TAG));
friend_hashmap.put(FULL_NAME_TAG, friend_json.getString(FULL_NAME_TAG));
friend_hashmap.put(GENDER_TAG, friend_json.getString(GENDER_TAG));
friend_hashmap.put(UPDATED_TIME_TAG, friend_json.getString(UPDATED_TIME_TAG));
friend_hashmap.put(LINK_TAG, friend_json.getString(LINK_TAG));
JSONObject friend_pic_wrapper = json.getJSONObject(PICTURE_TAG);
JSONObject friend_pic_data = friend_pic_wrapper.getJSONObject(DATA_TAG);
if (!friend_pic_data.getBoolean(IS_SILHOUETTE_TAG)) {
friend_hashmap.put(URL_TAG, friend_pic_data.getString(URL_TAG));
}
user_fb_friends.add(friend_hashmap);
Utils.log("A friend was added to user_fb_friends (" + i + ")");
}
JSONObject paging_wrapper = json.getJSONObject(PAGING_TAG);
String next_friends_json_url = null;
if (paging_wrapper.getString(NEXT_TAG) != null) {
next_friends_json_url = paging_wrapper.getString(NEXT_TAG);
}
JSONObject summary_wrapper = json.getJSONObject(SUMMARY_TAG);
if (next_friends_json_url != null) {
/*
* 3. Send a GET request for the next JSONObject
*/
get_paging_data(response);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
response = nextRequest.executeAndWait();
}
Before you go ahead and try to pars your JSON, first check what your JSON will look like. You can check that using Facebook's Graph Explorer at: https://developers.facebook.com/tools/explorer/
IMPORTANT: Only friends who installed this app are returned in API v2.0 and higher. total_count in summary represents the total number of friends, including those who haven't installed the app. More >>

Stream PDF Byte array from WebAPI to browser

I'm working in C#.net in a WebAPI...
I have...
WebAPI Controller...
public class GetSMBController : ApiController
{
public HttpResponseMessage GET(int AgencyID, string UserName)
{
var Pdfs = new HttpResponseMessage();
Pdfs = Utilities.Reporting.CreateStandardMapBooklet(AgencyID,UserName);
return Pdfs;
}
}
That calls a method...
public static HttpResponseMessage CreateStandardMapBooklet(int AgencyID, string userName)
{
string baseDataPath = #"\\dvfmweb4\\arcgisserver\basedata\";
string tempDataPath = #"\\dvfmweb4\arcgisserver\tempGrowerData\";
string unitTestSession = "UnitTestSession";
int ShadeType = 1;
bool isInImagery = false;
double MaxSceneSize = 1.5;
bool ScaleBar = true;
int MapSettingID = 0;
bool OverallPage = false;
bool OverallImagery = false;
bool IsRecordKeepingSheet = false;
int RecordKeepingSheetID = 0;
int TemplateID = 1480;
RCIS.Mapping.MapDomain.Reports.StandardMapBookletReport _Pdfs = new RCIS.Mapping.MapDomain.Reports.StandardMapBookletReport(
baseDataPath,
tempDataPath,
unitTestSession,
AgencyID,
ShadeType,
isInImagery,
MaxSceneSize,
ScaleBar,
MapSettingID,
TemplateID,
OverallPage,
OverallImagery,
false,
RecordKeepingSheetID,
userName,
true);
PDF testPDF = new PDF();
byte[] test = null;
try
{
List<RCIS.Mapping.MapDomain.Layout.CreatePdfResponse> pdf = _Pdfs.CreateReports();
foreach (var item in pdf)
{
//PDFInfo info = new PDFInfo();
//info.PdfBytes = item.PdfBytes;
testPDF.Report = item.PdfBytes;
test = item.PdfBytes;
}
}
catch(Exception e)
{
}
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(test)
};
response.Content = new ByteArrayContent(test);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline")
{
FileName = String.Format(AgencyID + userName + DateTime.Now.ToString("MMMddyyyy_HHmmss"))
};
response.Headers.CacheControl = new CacheControlHeaderValue()
{
MaxAge = new TimeSpan(0, 0, 60) // Cache for 30s so IE8 can open the PDF
};
return response;
}
Sorry for some of the commented out stuff and goofy variable names...I'm just trying to see if this is a viable thing.
the test object and HttpResponse message Content ARE populated but
I'm receiving this error when I call this from a browser...
This XML file does not appear to have any style information associated with it. The document tree is shown below.
An error has occurred.
Value cannot be null. Parameter name: content
System.ArgumentNullException
at System.Net.Http.ByteArrayContent..ctor(Byte[] content) at MappingServicesWebAPI.Utilities.Reporting.CreateStandardMapBooklet(Int32 AgencyID, String userName) in d:\FarmMaps\Web\WebAPI\MappingServicesWebAPI\MappingServicesWebAPI\Utilities\Reporting.cs:line 92 at MappingServicesWebAPI.Controllers.GetSMBController.GET(Int32 AgencyID, String UserName) in d:\FarmMaps\Web\WebAPI\MappingServicesWebAPI\MappingServicesWebAPI\Controllers\MappingController.cs:line 143 at lambda_method(Closure , Object , Object[] ) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.b__c(Object instance, Object[] methodParameters) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.<>c__DisplayClass5.b__4() at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)

How to add test case when post a test case result

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()));
}