Is it possible to store all test cases which have failed in a hashmap, and then call all values stored in the map at the end of a class?
Variable:
private HashMap<String, Integer> serverStatusMap = new HashMap<String, Integer>();
After Method Code:
#AfterMethod
public void trackServerStatus(ITestResult testResult) {
if (testResult.getStatus() == ITestResult.FAILURE) {
try {
String testName = this.getClass().getSimpleName().toString();
int serverStatus = ServerStatus.getResponseCode(basePage.getCurrentURL());
int i = 0;
while(i < serverStatusMap.size()) {
serverStatusMap.put(testName, serverStatus);
i++;
}
//serverStatusMap.put(testName, serverStatus);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Calling the stored values in the map After class:
#AfterClass
public void sendEmailBasedOnFailure(ITestContext context) throws WebDriverException, Exception {
String tempTime = new SimpleDateFormat("hh.mm.ss").format(new Date());
if(context.getFailedTests().size() > 0) {
SendEmailFile.sendEmailReport(
"TIME: " + tempTime + " | " + this.getClass().getPackage().toString(),
"TIME: " + tempTime + " | " + this.getClass().getPackage().toString() + " | " + "CLASS NAME: "
+ this.getClass().getSimpleName().toString() + "\n\n" +
"TOTAL NUMBER FAILED TESTS: " + context.getFailedTests().size() + "\n\n" +
"FAILED TEST CASES: " + context.getFailedTests().getAllMethods().toString() + "\n\n" +
serverStatusMap.toString());
}
Look at the last line of code: 'serverStatusMap.toString()'
Current Output of the Map:
{}
I do not understand what you are trying to do.
Do you want to send an email with failed tests?
Why not using the appropriate features like Listener or Reporter?
Have a look on the documentation about logging.
You have initialized variable "serverStatusMap". From below code
int i =0;
while(i < serverStatusMap.size()) {
serverStatusMap.put(testName, serverStatus);
i++;
}
I can see that i=0 and also serverStatusMap.size()=0. So it will never enter in while loop. so Finally when you print map there is nothing inside map. You need to change your while condition.
Related
I am currently facing an issue regarding this method getSurroundingSumGrid() which is supposed to take data from an earlier grid that was built based off of text file data and use it to determine new values within the array sumGrid. The STATICGRID array gets built at first with the correct values but then as the for loop continues on, the STATICGRID values change to what i have set sumGrid to change to. I don't have any defined code where STATICGRID is ever set to equal another value and if I did it should give an error.
public double[][] getSurroundingSumGrid() {
this.sumGrid = getBaseGrid();
for (int rowNum = 0; rowNum < sumGrid.length; rowNum++) {
final double[][] STATICGRID = this.getBaseGrid();
double topNum = 0, botNum = 0, rightNum = 0, leftNum = 0;
for (int colNum = 0; colNum < sumGrid[0].length; colNum++) {
try {
topNum = STATICGRID[rowNum - 1][colNum];
System.out.println("TOPNUM : (" + (rowNum-1) + "," + colNum + ") " + STATICGRID[rowNum-1][colNum]);
} catch (Exception e) {
topNum = STATICGRID[rowNum][colNum];
System.out.println("Top IndexOutOfBoundsException: " + STATICGRID[rowNum][colNum] + " used instead.");
}
try {
botNum = STATICGRID[rowNum + 1][colNum];
System.out.println("BOTNUM : (" + (rowNum+1) + "," + colNum + ") " + STATICGRID[rowNum+1][colNum]);
} catch (Exception e) {
botNum = STATICGRID[rowNum][colNum];
System.out.println("Bot IndexOutOfBoundsException: " + STATICGRID[rowNum][colNum] + " used instead.");
}
try {
leftNum = STATICGRID[rowNum][colNum - 1];
System.out.println("LEFTNUM : (" + rowNum + "," + (colNum-1) + ") " + STATICGRID[rowNum][colNum-1]);
} catch (Exception e) {
leftNum = STATICGRID[rowNum][colNum];
System.out.println("Left IndexOutOfBoundsException: " + STATICGRID[rowNum][colNum] + " used instead.");
}
try {
rightNum = STATICGRID[rowNum][colNum + 1];
System.out.println("RIGHTNUM : (" + rowNum + "," + (colNum+1) + ") " + STATICGRID[rowNum][colNum+1]);
} catch (Exception e) {
rightNum = STATICGRID[rowNum][colNum];
System.out.println("Right IndexOutOfBoundsException: " + STATICGRID[rowNum][colNum] + " used instead.");
}
this.sumGrid[rowNum][colNum] = topNum + botNum + rightNum + leftNum;
System.out.println("STATICGRID NEW NUM : " + STATICGRID[rowNum][colNum]);
System.out.println("SUMGRID NEW NUM : " + sumGrid[rowNum][colNum]);
}
}
return this.sumGrid;
}
When doing these tests with the code I can see very clearly that the data in both arrays are changing overtime, and in turn giving me wrong results. I've tried for about 2 hours just moving things around and can't seem to figure out how to get this to work properly.
As you can even see, I even attempted rebuilding the STATICGRID array every single time the for loop completed and it wouldn't even hinder the result. It does the same thing regardless of where you put the STATICGRID at (either outside or inside at the top-most level of the for loop, and it doesn't matter whether it's final or not), it does the same thing. After looking at it for so long I'm beyond confused on why my code isn't working and I have a slight feeling that it is the try-catch statement but I wouldn't at all know why. I don't know a ton about the statement and what it does entirely but the reason it is there is because the data can get an IndexOutOfBoundsException so instead of getting that it would instead count itself for each IndexOutOfBoundsException it got as per the assignment instructions.
Thanks and I hope this makes sense.
Alright, thanks to FredK's suggestion at using a deepCopy, I did some research and used this method to get better results. This is the unoptomizedDeepCopy by Philip Isehour. I don't exactly understand it but I'm going to just use it for now and spend some time learning more about this and how they work. I'm currently a CS221 student and we haven't gone over deepCopy yet.
public static Object deepCopy(Object orig) {
Object obj = null;
try {
// Write the object out to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(orig);
out.flush();
out.close();
// Make an input stream from the byte array and read
// a copy of the object back in.
ObjectInputStream in = new ObjectInputStream(
new ByteArrayInputStream(bos.toByteArray()));
obj = in.readObject();
}
catch(IOException e) {
e.printStackTrace();
}
catch(ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
return obj;
}
After this method, I then was able to stop the array from changing value by using this in front of the getBaseGrid() method.
public double[][] getSurroundingSumGrid() {
this.sumGrid = (double[][]) GridMonitor.deepCopy(this.getBaseGrid());
double[][] staticGrid = (double[][]) GridMonitor.deepCopy(this.getBaseGrid());
double topNum, botNum, rightNum, leftNum;
for (int rowNum = 0; rowNum < sumGrid.length; rowNum++) {
for (int colNum = 0; colNum < sumGrid[0].length; colNum++) {
try {
topNum = staticGrid[rowNum - 1][colNum];
} catch (Exception e) {
topNum = staticGrid[rowNum][colNum];
}
try {
botNum = staticGrid[rowNum + 1][colNum];
} catch (Exception e) {
botNum = staticGrid[rowNum][colNum];
}
try {
leftNum = staticGrid[rowNum][colNum - 1];
} catch (Exception e) {
leftNum = staticGrid[rowNum][colNum];
}
try {
rightNum = staticGrid[rowNum][colNum + 1];
} catch (Exception e) {
rightNum = staticGrid[rowNum][colNum];
}
this.sumGrid[rowNum][colNum] = topNum + botNum + rightNum + leftNum;
}
}
return this.sumGrid;
}
Thanks!
I try to save tweets with keywords, I know that free API gives only 7 days of the result, but it never gets any set of a timeline greater than few hours, sometimes it even gives me a range of an hour. I did set since() and until() to the searching query. The maximum number of the tweets I've got from a single run was less than 400. And can anyone tell me why it stopped automatically with such few results? Thanks.
public static void main(String[] args) throws TwitterException {
String KEY_word;
String Exclude;
String Since;
String Until;
String OPT_dir;
String time;
int x;
Propertyloader confg = new Propertyloader();
KEY_word = confg.getProperty("KEY_word");
Exclude = confg.getProperty("Exclude");
Since = confg.getProperty("Since");
Until = confg.getProperty("Until");
OPT_dir = confg.getProperty("OPT_dir");
Twitter twitter = new TwitterFactory().getInstance();
try {
time = new SimpleDateFormat("yyyyMMddHHmm'.txt'").format(new Date());
x = 1;
Query query = new Query(KEY_word + Exclude);
query.since(Since);
query.until(Until);
QueryResult result;
do {
result = twitter.search(query);
List<Status> tweets = result.getTweets();
for (Status tweet : tweets) {
try {
String filedir = OPT_dir + KEY_word + time;
writeStringToFile(filedir, x + ". " + "#" + tweet.getUser().getScreenName() + ", At: " + tweet.getCreatedAt() + ", Rt= " + tweet.getRetweetCount() + ", Text: " + tweet.getText());
x += 1;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} while ((query = result.nextQuery()) != null);
System.exit(0);
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to search tweets: " + te.getMessage());
System.exit(-1);
}
}
public static void writeStringToFile(String filePathAndName, String stringToBeWritten) throws IOException{
try
{
String filename= filePathAndName;
boolean append = true;
FileWriter fw = new FileWriter(filename,append);
fw.write(stringToBeWritten);//appends the string to the file
fw.write("\n" +"\n");
fw.close();
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
}
}
You can get more tweets by using setMaxId. Here is an example :
long lowestTweetId = Long.MAX_VALUE;
x = 1;
Query query = new Query("stackoverflow");
query.since("2018-08-10");
query.until("2018-08-16");
query.setCount(100); //The number of tweets to return per page, up to a maximum of 100. Defaults to 15. https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets.html
query.setResultType(Query.RECENT); // to get an order
int searchResultCount=100;
QueryResult result;
do {
result = twitter.search(query);
List<Status> tweets = result.getTweets();
for (Status tweet : tweets) {
try {
System.out.println( "#" + tweet.getUser().getScreenName() + ", At: " + tweet.getCreatedAt() );
x += 1;
if (tweet.getId() < lowestTweetId) {
lowestTweetId = tweet.getId();
query.setMaxId(lowestTweetId-1);
}
else {// each new maxid should be smaller than the other one so break here
//do whatever you want to handle it ex: break from two loops
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} while (searchResultCount != 0 );
public String generateDataPDF() {
System.out.println("Inside generate PDF");
String filePath = "";
HttpSession sess = ServletActionContext.getRequest().getSession();
try {
sess.setAttribute("msg", "");
if (getCrnListType().equalsIgnoreCase("F")) {
try {
filePath = getModulePath("CRNLIST_BASE_LOCATION") + File.separator + getCrnFileFileName();
System.out.println("File stored path : " + filePath);
target = new File(filePath);
FileUtils.copyFile(crnFile, target);
} catch (Exception e) {
System.out.println("File path Exception " + e);
}
}
System.out.println("Values from jsp are : 1)Mode of Generation : " + getCrnListType() + " 2)Policy Number : " + getCrnNumber() + " 3)Uploaded File Name : " + getCrnFileFileName() + " 4)LogoType : " + getLogoType()
+ " 5)Output Path : " + getOutputPath() + " 6)Type of Generation : " + getOptionId() + " 7)PDF Name : " + getPdfName());
String srtVAL = "";
String arrayVaue[] = new String[]{getCrnListType(), getCrnListType().equalsIgnoreCase("S") ? getCrnNumber() : filePath, getLogoType().equalsIgnoreCase("WL") ? "0" : "1",
getOutputPath(), getGenMode(), getRenType()};
//INS DB Connection
con = getInsjdbcConnection();
ArrayList selectedCRNList = new ArrayList();
String selectedCRNStr = "";
selectedCRNStr = getSelectedVal(selectedCRNStr, arrayVaue[1]);
String[] fileRes = selectedCRNStr.split("\\,");
if (fileRes[0].equalsIgnoreCase("FAIL")) {
System.out.println("fileRes is FAIL beacause of other extension file.");
sess.setAttribute("pr", "Please upload xls or csv file.");
return SUCCESS;
}
System.out.println("List file is : " + selectedCRNStr);
String st[] = srtVAL.split("[*]");
String billDateStr = DateUtil.getStrDateProc(new Date());
Timestamp strtPasrsingTm = new Timestamp(new Date().getTime());
String minAMPM = DateUtil.getTimeDate(new Date());
String str = "";
String batchID = callSequence();
try {
System.out.println("Inside Multiple policy Generation.");
String userName=sess.getAttribute("loginName").toString();
String list = getProcessesdList(userName);
if (list != null) {
System.out.println("list is not null Users previous data is processing.....");
//setTotalPDFgNERATEDmSG("Data is processing please wait.");
sess.setAttribute("pr","Batch Id "+list+" for User " + userName + " is currently running.Please wait till this Process complete.");
return SUCCESS;
}
String[] policyNo = selectedCRNStr.split("\\,");
int l = 0, f = 0,counter=1;
for (int j = 0; j < policyNo.length; j++,counter++) {
String pdfFileName = "";
int uniqueId=counter;
globUniqueId=uniqueId;
insertData(batchID, new Date(), policyNo[j], getOptionId(), userName,uniqueId);
System.out.println("Executing Proc one by one.");
System.out.println("policyNo[j]" + policyNo[j]);
System.out.println("getOptionId()" + getOptionId());
System.out.println("seqValue i.e batchId : " + batchID);
}
str = callProcedure(policyNo[j], getOptionId(), batchID);
String[] procResponse = str.split("\\|");
for (int i = 0; i < procResponse.length; i++) {
System.out.println("Response is : " + procResponse[i]);
}
if (procResponse[0].equals("SUCCESS")) {
Generator gen = new Generator();
if (getPdfName().equalsIgnoreCase("true")) {
System.out.println("Checkbox is click i.e true");
pdfFileName = procResponse[1];
} else {
System.out.println("Checkbox is not click i.e false");
String POLICY_SCH_GEN_PSS = getDetailsForFileName(userName, policyNo[j], batchID);
String[] fileName = POLICY_SCH_GEN_PSS.split("\\|");
if (getLogoType().equals("0") || getLogoType().equals("2")) {
System.out.println("If logo is O or 1");
pdfFileName = fileName[1];
} else if (getLogoType().equals("1")) {
System.out.println("If logo is 2");
pdfFileName = fileName[0];
}
}
b1 = gen.genStmt(procResponse[1], procResponse[2], "2", getLogoType(), "0", pdfFileName,"1",userName,batchID);
l++;
updateData(uniqueId,batchID, "Y");
} else {
f++;
updateData(uniqueId,batchID, "F");
}
}
sess.setAttribute("pr","Total "+l+" "+getGenericModulePath("PDF_RES1") + " " + " " + getGenericModulePath("PDF_RES2") + " " + f);
}catch (Exception e) {
updateData(globUniqueId,batchID, "F");
System.out.println("Exception in procedure call");
setTotalPDFgNERATEDmSG("Fail");
e.printStackTrace();
sess.setAttribute("pr", "Server Error.");
return SUCCESS;
}
}catch (Exception ex) {
ex.printStackTrace();
sess.setAttribute("pr", "Server Error.");
return SUCCESS;
}
System.out.println("Above second return");
return SUCCESS;
}
GenerateDataPDf method generates PDF based on the parameters i.e ProductType(GenMode),CrnList(uploaded in excel file...)Code works fine when only single user generates PDF. But If two different User(User and roles are assigned in application) start the process same time request paraeters are overridden then! Suppose first user request pdf for 50 customers for product 1. User1's process is still running and second user request for product2. Now User1's pdf are generated but for product2.....! Here batchId is unique for every single request.One table is maintained where batch_id,all pdf,generation flags are mainained there. How do I solve this?
As per your comment, this is what I would do, It's probably not the best way to do !
Firstly : Create a function to collet all your data at the beginning. You should not modify/update/create anything when you are generating a PDF. IE : array/list collectPDFData() wich should retourn an array/list.
Secondly : Use a synchronized methods like synchronized boolean generatePDF(array/list)
"Synchronized" methods use monitor lock or intrinsic lock in order to manage synchronization so when using synchronized, each method share the same monitor of the corresponding object.
NB : If you use Synchronize, it's probably useless to collect all your data in a separate way, but I think it's a good practice to make small function dedicated to a specific task.
Thus, your code should be refactored a little bit.
Greetings I'm would like to read the data of a method I try to change with Bytecode manipulation with javassist and a java agent.
The reason is that my program (a webApplication) won't work (javassist.CannotCompileException: [source error] ) is missing what is this?)
and no one could help me at the moment .
So I wanna no what is inside my Methode maybe something produces a bug ... so I want to know if I can read and print the content of a CtMethod
My code
private byte[] transformClass(Class classToTransform, byte[] b, String className) {
if (className.startsWith("de/example")) {
ClassPool pool = ClassPool.getDefault();
CtClass cl = null;
try {
cl = pool.makeClass(new ByteArrayInputStream(b));
} catch (IOException e) {
e.printStackTrace();
}
try {
assert cl != null;
for (CtMethod ctMethod : cl.getMethods()) {
changeMethod(ctMethod);
System.out.println(ctMethod.getMethodInfo());
System.out.println(ctMethod.getMethodInfo2());
}
b = cl.toBytecode();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cl != null) {
cl.detach();
}
}
}
return b;
}
private void changeMethod(CtMethod method) throws NotFoundException, CannotCompileException {
if (method.hasAnnotation(Loggable.class)) {
System.out.println(method.getMethodInfo());
System.out.println(method.getMethodInfo2());
method.insertBefore(" startTime = 0;\n" +
" startTime = System.currentTimeMillis();\n" +
" final de.example.webservice.ws.TestFolder.Logging threadLogger = de.example.webservice.ws.TestFolder.Logging.getInstance();\n" +
" Thread thread1 = new Thread(new Runnable(){\n" +
" #Override\n" +
" public void run() {\n" +
" threadLogger.info(\"Testlog\");\n" +
" try {\n" +
" threadLogger.logCall(Webservice.this.getClass().getMethod(\"startThread0\"),\"Thread\");\n" +
" } catch (Exception e) {\n" +
" e.printStackTrace();\n" +
" }\n" +
" }\n" +
" });\n" +
" thread1.start();");
}
}
I just Methods at google who can read data from files like a .txt file but that isn't usefull for my problem.
If you're trying to read the original source of the method, javassist doesn't really do that. You need a java bytecode decompiler. Google for that term. jad is a good one.
My videos.dat contains some objects were stored by: V - 1000 * disks + AI
Video<ID; Name; Disk; $Fee>
Video<V1001; Avenger; 1; $12.0>
Video<V1002; 50 First Dates; 1; $13.0>
Video<V2001; Furious 7; 2; $18.0>
And my StartUp() load to my GUI. At the startup how can I count and continue to add video Objects following auto incremental rule.
public void startUp() {
int count = 0;
try {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("videos.dat"))) {
objects = (Vector) ois.readObject();
for (Object v : objects) {
System.out.println(v.toString());
count++;
fireObjectCreated(v);
}
ois.close();
} catch (SecurityException ex) {
Logger.getLogger(VideoManager.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalArgumentException ex) {
Logger.getLogger(VideoManager.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Got " + count + " video objects");
} catch (FileNotFoundException ex) {
System.err.println("FileNotFoundException");
} catch (IOException ex) {
System.err.println("IOException");
} catch (ClassNotFoundException ex) {
System.err.println("ClassNotFoundException");
}
}
I'm using HashMap to store and auto increment but after startup() my program go back to start means it started from Video V1001
public static int currentNumberOfStaticVideoID(int value) {
if (listCountVideoID.containsKey(value)){
System.out.println("Contain disk type " +value + " : " + listCountVideoID.containsKey(value));
int id = listCountVideoID.get(value);
System.out.println("Get current id: " + id);
int newid = id + 1;
listCountVideoID.put(value, newid);
System.out.println("New id: " + newid);
return newid;
}
int newKey = value*1000;
listCountVideoID.put(value, newKey);
return newKey;
}
public static Map<Integer, Integer> listCountVideoID = new HashMap<Integer,Integer>();
So, anyone can help to figure out some goals:
+ load the data file >> load objects
+ continue store video with ID = "V" + 1000*disk + AutoIncre
+ if disk = 1 > continue from V1003
+ if disk = 2 > continue from V2002