This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 6 years ago.
I'm reading emails using JavaMail API and adding each message (along with sender, sent date etc) to a LinkedHashMap. Next I'm adding the LinkedHashMap to an ArrayList of LinkedHashMaps. However, the odd thing is that the entire Hashmapis being overwritten by the last entry.
I have the following code:
private ArrayList<LinkedHashMap<String, String>> readAllMsgsFromOutlook() throws FileNotFoundException, IOException, MessagingException
{
LinkedHashMap<String, String> msgsLinkedHashMap = new LinkedHashMap<String, String>();
ArrayList<LinkedHashMap<String, String>> msgsLinkedHashMapAsArrayList = new ArrayList<LinkedHashMap<String, String>>();
//String host = "smtp-mail.outlook.com";
String emailID = ..getEmail();
String password = ..getPassword();
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap-mail.outlook.com", emailID, password);
Folder inboxFolder = store.getFolder("INBOX");
UIDFolder UID = (UIDFolder)inboxFolder;
Message[] msgs = null;
Flags seen = new Flags(Flags.Flag.SEEN);
FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
msgs = inboxFolder.search(unseenFlagTerm);
System.out.println("Number of New Emails in Inbox: " + msgs.length + "\n");
String senderAsString = "";
String sentDateAsString = "";
String subjectAsString = "";
String contentAsString = "";
String UIDAsString = "";
for (int msgCounter = 0; msgCounter < msgs.length; msgCounter++)
{
System.out.println("Email #: " + (msgCounter + 1) + "\n");
Message msg = msgs[msgCounter];
long UIDAsLong = UID.getUID(msg);
Object content = msg.getContent();
if (content instanceof String)
{
System.out.println("Email is instance of String: \n");
Address[] sender = msg.getFrom();
senderAsString = sender[0].toString();
System.out.println("SENDER: " + senderAsString);
sentDateAsString = msg.getSentDate().toString();
System.out.println("SENT_DATE: " + sentDateAsString);
subjectAsString = msg.getSubject().toString();
System.out.println("SUBJECT: " + subjectAsString);
contentAsString = (String)content;
System.out.println("CONTENT: " + contentAsString);
UIDAsString = String.valueOf(UIDAsLong);
System.out.println("UID: " + UIDAsString);
System.out.println("\n");
}
else if (content instanceof Multipart)
{
System.out.println("Email is instance of Multipart");
Multipart mp = (Multipart)content;
BodyPart bp = mp.getBodyPart(0);
Address[] sender = msg.getFrom();
sentDateAsString = msg.getSentDate().toString();
subjectAsString = msg.getSubject();
contentAsString = bp.getContent().toString();
senderAsString = sender[0].toString();
System.out.println("SENDER: " + senderAsString);
System.out.println("SENT DATE: " + sentDateAsString);
System.out.println("SUBJECT: " + subjectAsString);
System.out.println("CONTENT: " + contentAsString);
UIDAsString = String.valueOf(UIDAsLong);
System.out.println("UID: " + UIDAsString);
System.out.println("\n");
}
msgsLinkedHashMap.put("sender", senderAsString);
msgsLinkedHashMap.put("sentDate", sentDateAsString);
msgsLinkedHashMap.put("subject", subjectAsString);
msgsLinkedHashMap.put("content", contentAsString);
msgsLinkedHashMap.put("UID", UIDAsString);
msgsLinkedHashMapAsArrayList.add(msgsLinkedHashMap);
}
} catch (Exception mex) {
// TODO Auto-generated catch block
mex.printStackTrace();
}
At this point the content that is added seems to be correct. For example, if I had 24 messages and the content was "msg1", "msg2", "msg3" etc then this system prints out the correct content.
However when I loop through the HashMap after the following closing brackets all I get is the 24th element. In other words, the system will always print "msg24" even for the first 23 elements in list in the following code:
for (int arrayListCounter = 0; arrayListCounter < msgsLinkedHashMapAsArrayList.size(); arrayListCounter++) {
LinkedHashMap<String, String> singleHashmapInArrayList = msgsLinkedHashMapAsArrayList.get(arrayListCounter);
String content = singleHashmapInArrayList.get("content");
System.out.println(">>> " + arrayListCounter + " : " + content);
// For some reason content is always equal to msg24 instead of msg1, msg2, msg3 etc. It seems like the 24th element is replacing all previous elements. But why?
}
return msgsLinkedHashMapAsArrayList;
}
I've been trying to figure out the problem for hours.
What am I doing wrong?
As you assigned msgsLinkedHashMap variable outside the loop you're always editing the same object and keep adding it's instance to the list. The solution is to move
Map<String, String> msgsLinkedHashMap = new LinkedHashMap<String, String>();
inside your for loop so you'll be creating new instance of Map on each iteration.
Related
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
I'll explain the logic: I am reading a XML file which contain many request and responses in soap format then I'm storing the request and response in two Hash map. In first Hash map I'm storing transaction Id(unique) as key and values as request time,til-name. In second hash map I'm storing transaction Id(unique) as key and values as response time. In both hash map the keys are same but values are different, by using for loop iterating two loops and I need to get the time difference between response time and request time
eg:request time:2020-01-30T11:07:08.351Z and response time:2020-01-30T11:07:10.152Z
public class MapTimeDiff {
public static void main(String[] args) throws ParseException {
File file =new File("C:\\Users\\gsanaulla\\Documents\\My Received Files\\ecarewsframework.xml");
Scanner in = null;
String tilname = null;
String transactionId = null;
String requesttime = null;
String responsetime = null;
Date dateOne = null;
Date dateTwo = null;
double timeDiff;
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Map<String,ArrayList<String>> request=new HashMap<String,ArrayList<String>>();
ArrayList<String> req=new ArrayList<String>();
Map<String,ArrayList<String>> response=new HashMap<String,ArrayList<String>>();
ArrayList<String> res=new ArrayList<String>();
try {
in = new Scanner(file);
while(in.hasNext())
{
String line=in.nextLine();
if(line.contains("</S:Envelope>")) {
System.out.println(line);
tilname=line.split("StartRecord><")[1].split("><")[0].split(":")[1];
System.out.println("tilname :: "+tilname);
transactionId = line.split("transactionId>")[1].split("<")[0];
System.out.println("transactio id :: "+transactionId);
requesttime=line.split("sourceTimestamp>")[1].split("<")[0];
System.out.println("request time is :: "+requesttime);
dateOne = df.parse(requesttime);
}
req.add(tilname);
req.add(dateOne.toString());
System.out.println("req is==== " +req);
request.put(transactionId,req);
System.out.println("request is==== " +request.get(transactionId));
if(line.contains("</SOAP-ENV:Envelope>")) {
//System.out.println(line);
if(line.contains("transactionId"))
{
responsetime=line.split("sourceTimestamp>")[1].split("<")[0];
transactionId = line.split("transactionId>")[1].split("<")[0];
System.out.println("responsetime :: "+responsetime);
System.out.println("transaction id "+transactionId);
dateTwo = df.parse(responsetime);
}
res.add(dateTwo.toString());
System.out.println("res is===== "+res);
response.put(transactionId,res);
System.out.println("response is===== "+response.get(transactionId));
for (Entry<String, ArrayList<String>> entry : request.entrySet()) {
for (Entry<String, ArrayList<String>> entry1 : response.entrySet()) {
System.out.println("Key = " + entry.getKey() +
", Value = " + entry.getValue());
System.out.println("Key = " + entry1.getKey() +
", Value = " + entry1.getValue());
if(request.keySet().equals(response.keySet())) {
timeDiff = (dateTwo.getTime() - dateOne.getTime());
}
}
}
}
}
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I'm not sure if I understood your question correctly but maybe you can do something similiar like the following:
Map<String, List<String>> requests = Map.of("1", List.of("10,13,12"), "2", List.of("8,7,9"), "3", List.of("11"));
Map<String, List<String>> responses = Map.of("1", List.of("9,10,14"), "2", List.of("8,9,6,12"));
for(Map.Entry<String, List<String>> requestEntry : requests.entrySet()) {
String transactionId = requestEntry.getKey();
if(responses.containsKey(transactionId)) {
System.out.println("Transaction Id: " + transactionId);
for(int i = 0; i < min(requestEntry.getValue().size(), responses.get(transactionId).size()); i++) {
List<String> requestTimes = asList(requestEntry.getValue().get(i).split(","));
List<String> responseTimes = asList(responses.get(transactionId).get(i).split(","));
for(int j = 0; j < min(requestTimes.size(), responseTimes.size()); j++) {
int requestTime = parseInt(requestTimes.get(j));
int responseTime = parseInt(responseTimes.get(j));
System.out.println("Difference: " + abs(requestTime - responseTime));
}
}
}
}
As you can see there are no responses for transactionId 3 so this will be ignored.
If elements in the list for a key differ in size (transactionId 2) the surplus elements will also be ignored.
Transaction Id: 1
Difference: 1
Difference: 3
Difference: 2
Transaction Id: 2
Difference: 0
Difference: 2
Difference: 3
Trying to pull the list of users from large AD Groups via Java - but only get 1500 back - how can I get all the users?
// Step1 method - Pulling ADGroups from Active Directory
private static void getADGroups() {
Hashtable<String, Object> env = new Hashtable<String, Object>(11);
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://");
env.put(Context.SECURITY_PRINCIPAL, "xxxx");
env.put(Context.SECURITY_CREDENTIALS, "1233");
env.put(Context.REFERRAL, "follow");
LdapContext ctx = null;
try {
ctx = new InitialLdapContext(env, null);
// Activate paged results
int pageSize = 10000;
byte[] cookie = null;
ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });
int total;
do {
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String[] attrIDs = { "cn" };
searchControls.setReturningAttributes(attrIDs);
String searchBase = "OU=Groups,DC=cof,DC=ds,DC=com";
String searchFilter = "CN=*Ranger*";
/* perform the search */
NamingEnumeration results = ctx.search(searchBase, searchFilter, searchControls);
/* for each entry print out name + all attrs and values */
int count = 0;
while (results != null && results.hasMore()) {
SearchResult entry = (SearchResult) results.next();
//System.out.println(count + ")" + entry.getName());
count = count + 1;
String gname = entry.getName();
//System.out.println("gname before split " + gname);
String[] gnames = gname.split(",");
gname = gnames[0];
//System.out.println("gname after split - 1 " + gname);
gname = gname.substring(3);
//System.out.println("gname after split - 2 " + gname);
groups.add(gname);
}
//System.out.println("count : " + count);
// Examine the paged results control response
Control[] controls = ctx.getResponseControls();
//System.out.println("controls-size : " + controls.length);
if (controls != null) {
for (int i = 0; i < controls.length; i++) {
if (controls[i] instanceof PagedResultsResponseControl) {
PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
total = prrc.getResultSize();
//System.out.println("total : " + total);
if (total != 0) {
//System.out.println("*****************
cookie = prrc.getCookie();
//System.out.println("cookie : " + cookie);
}
}
} else {
System.out.println("No controls were sent from the server");
}
// Re-activate paged results
ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });
} while (cookie != null);
} catch (NamingException e) {
System.out.println("PagedSearch failed." + e.getMessage());
e.printStackTrace();
} catch (IOException ie) {
System.out.println("PagedSearch failed." + ie.getMessage());
ie.printStackTrace();
} finally {
try {
ctx.close();
} catch (NamingException e) {
System.out.println("PagedSearch failed (error occured in closing context)." + e.getMessage());
e.printStackTrace();
}
}
}
// Step2 method - to pull users from ADgroups that we got for above
private static void getGroupMembers(String groupName) {
searchBase = "Ou=users";
String returnedAtts[] = { "member" };
searchControls.setReturningAttributes(returnedAtts);
searchFilter = String.format("(cn=%s)", groupName);
// System.out.println(searchFilter);
getSearchResult();
filterSearchResultsForGroupMembers(groupName);
} // end of method.
`
The key is where you request the member attribute. If you get back exactly 1500 results, you know there might be more. This is how you request the next batch:
String[] returnedAtts = { "member;range=1500-*" };
Then if you get exactly 1500 back again, you need to ask for more (`member;range=3000-*1). Keep asking for more until you get less than 1500 back.
So setup a loop with a counter and use that counter in the range string.
There is a full example here (search the page for "setReturningAttributes" to find that section of the code): https://community.oracle.com/thread/1157644
i Need To Verify Email is Received or not in gmail. So That i Tried The Following Code. But i Didn't Get The Result. Can You Please Sort Me out This.
The Following Code is :
public static void getPassword(String email, String password) throws Exception {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", email, password);
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
System.out.println("Total Message:" + folder.getMessageCount());
System.out.println("Unread Message:" + folder.getUnreadMessageCount());
Message[] messages = null;
boolean isMailFound = false;
Message mailFromProx = null;
// Search for mail from Prox with Subject = 'Email varification Testcase'
for (int i = 0; i <= 5; i++) {
messages = folder.search(new SubjectTerm("Email varification Testcase"), folder.getMessages());
// Wait for 20 seconds
if (messages.length == 0) {
Thread.sleep(20000);
}
}
// Search for unread mail
// This is to avoid using the mail for which
// Registration is already done
for (Message mail : messages) {
if (!mail.isSet(Flags.Flag.SEEN)) {
mailFromProx = mail;
System.out.println("Message Count is: " + mailFromProx.getMessageNumber());
isMailFound = true;
}
}
// Test fails if no unread mail was found
if (!isMailFound) {
throw new Exception("Could not find new mail from iGotThis :-(");
// Read the content of mail and get password
} else {
String line;
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(mailFromProx.getInputStream()));
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
System.out.println(buffer);
String result = buffer.toString().substring(buffer.toString().indexOf("is:") + 1,
buffer.toString().indexOf("3. Start enjoying an easier life!"));
String resultxx = result.substring(4, result.length() - 1);
//Print passsword
System.out.println(resultxx);
Properties prop = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream(Constant.Path_UserPassFile);
// set the properties value in property file
prop.setProperty("User_Password", resultxx);
PropsUtils.setProperties().setProperty("User_Password", resultxx);
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
}
System.out.println("Password = " + prop.getProperty("User_Password"));
}
}
}
i Tried Searching Lot of Results , But Nothing Not Clear. Can You Please Provide Me Prefect Result.
if You Got Any Results Regarding The Mail Testing in Selenium Please Provide Here , Let Me Try Here.
Here is the working solution for your problem. It uses JAVAX MAIL API and JAVA code.
It does a lot more, so remove the code that u don't need.
public GmailUtils(String username, String password, String server, EmailFolder
emailFolder) throws Exception {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imap");
props.setProperty("mail.imaps.partialfetch", "false");
props.put("mail.imap.ssl.enable", "true");
props.put("mail.mime.base64.ignoreerrors", "true");
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imap");
store.connect("imap.gmail.com", 993, "<your email>", "<your password>");
Folder folder = store.getFolder(emailFolder.getText());
folder.open(Folder.READ_WRITE);
System.out.println("Total Messages:" + folder.getMessageCount());
System.out.println("Unread Messages:" + folder.getUnreadMessageCount());
messages = folder.getMessages();
for (Message mail : messages) {
if (!mail.isSet(Flags.Flag.SEEN)) {
System.out.println("***************************************************");
System.out.println("MESSAGE : \n");
System.out.println("Subject: " + mail.getSubject());
System.out.println("From: " + mail.getFrom()[0]);
System.out.println("To: " + mail.getAllRecipients()[0]);
System.out.println("Date: " + mail.getReceivedDate());
System.out.println("Size: " + mail.getSize());
System.out.println("Flags: " + mail.getFlags());
System.out.println("ContentType: " + mail.getContentType());
System.out.println("Body: \n" + getEmailBody(mail));
System.out.println("Has Attachments: " + hasAttachments(mail));
}
}
}
public boolean hasAttachments(Message email) throws Exception {
// suppose 'message' is an object of type Message
String contentType = email.getContentType();
System.out.println(contentType);
if (contentType.toLowerCase().contains("multipart/mixed")) {
// this message must contain attachment
Multipart multiPart = (Multipart) email.getContent();
for (int i = 0; i < multiPart.getCount(); i++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(i);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
System.out.println("Attached filename is:" + part.getFileName());
MimeBodyPart mimeBodyPart = (MimeBodyPart) part;
String fileName = mimeBodyPart.getFileName();
String destFilePath = System.getProperty("user.dir") + "\\Resources\\";
File fileToSave = new File(fileName);
mimeBodyPart.saveFile(destFilePath + fileToSave);
// download the pdf file in the resource folder to be read by PDFUTIL api.
PDFUtil pdfUtil = new PDFUtil();
String pdfContent = pdfUtil.getText(destFilePath + fileToSave);
System.out.println("******---------------********");
System.out.println("\n");
System.out.println("Started reading the pdfContent of the attachment:==");
System.out.println(pdfContent);
System.out.println("\n");
System.out.println("******---------------********");
Path fileToDeletePath = Paths.get(destFilePath + fileToSave);
Files.delete(fileToDeletePath);
}
}
return true;
}
return false;
}
public String getEmailBody(Message email) throws IOException, MessagingException {
String line, emailContentEncoded;
StringBuffer bufferEmailContentEncoded = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(email.getInputStream()));
while ((line = reader.readLine()) != null) {
bufferEmailContentEncoded.append(line);
}
System.out.println("**************************************************");
System.out.println(bufferEmailContentEncoded);
System.out.println("**************************************************");
emailContentEncoded = bufferEmailContentEncoded.toString();
if (email.getContentType().toLowerCase().contains("multipart/related")) {
emailContentEncoded = emailContentEncoded.substring(emailContentEncoded.indexOf("base64") + 6);
emailContentEncoded = emailContentEncoded.substring(0, emailContentEncoded.indexOf("Content-Type") - 1);
System.out.println(emailContentEncoded);
String emailContentDecoded = new String(new Base64().decode(emailContentEncoded.toString().getBytes()));
return emailContentDecoded;
}
return emailContentEncoded;
}
I would suggest you to use Nada email api which are disposable email addresses and very easy to get the content.
Check the examples here.
http://www.testautomationguru.com/selenium-webdriver-email-validation-with-disposable-email-addresses/
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());
}
}