If-Else condition is not working for my test case - java

I am writing an if-else condition in my test case. But function not going in else condition , it just look for if (condition).I am not able to figure out the problem.
Using java with selenium webdriver
public static void afterMenthod() throws InterruptedException {
try {
if (remoteDriver.findElementByName("Confirmation").isDisplayed())
{
if (remoteDriver.findElementByName("Stop").isDisplayed())
{
remoteDriver.findElementByName("Stop").click();
}
else
{
remoteDriver.findElementByName("Resume").click();
remoteDriver.findElementByName("Navigate up").click();
remoteDriver.findElementByName("Stop").click();
}
}
else if (remoteDriver.findElementByName("TRY AGAIN").isDisplayed())
{
System.out
.println("There is some problem in deposit transaction");
remoteDriver.findElementByName("Navigate up").click();
remoteDriver.findElementByName("Stop").click();
remoteDriver.findElementByName("Stop").click();
}
else if (remoteDriver.findElementByName("NEXT").isDisplayed() || remoteDriver.findElementByName("SUBMIT").isDisplayed() )
{
System.out.println("There is some problem in deposit transaction");
remoteDriver.findElementByName("Navigate up").click();
remoteDriver.findElementByName("Stop").click();
}
else {
// if(remoteDriver.findElementByName("namaskaar").isDisplayed())
System.out
.println("There is some problem in deposit transaction");
}
} finally{
GeneralMethods.signout();
System.out.println("Script Over");
}}
It just look for "confirmation" element, if it does not find that test get fails.

Try checking whether the element is displayed AND enabled
WebElement confirmation = remoteDriver.findElementByName("Confirmation");
if ( confirmation.isDisplayed() && confirmation.isEnabled()) {
...
}
else {
...
}

Write Your Else Part In catch block.
This way if an exception occurs, your else block will get executed.
It worked for me.
My Code to find a element in scroll-able screen and click it.
public static void scrollToBeFound(String Value) throws InterruptedException{
try{
driver.findElementByName(Value).click();
Thread.sleep(5000);
}
catch(Exception e){
try{
driver.swipe(120,420,120,750,1500);
Thread.sleep(3000);
driver.findElementByName(Value).click();
}
catch(Exception ex){
driver.swipe(120,750,120,420,1500);
Thread.sleep(3000);
driver.findElementByName(Value).click();
}
}
}

"It just look for "confirmation" element, if it does not find that test get fails." - that's because findElementByName throws an exception if element is not found. Which is why the else is not getting processed. You need to use try-catch-finally in your code. Search any forum on how to use it.

Related

Run Java program after exception encountered

How can I make my Java run again from the start (main) when it encounters an exception without closing and running it again manually?
My program basically writes on a file. When it cannot find the file I will throw the FileNotFoundException then write the file (say for example hello.txt). After it writes, the program closes (in NetBeans cause I am still developing it) and start showing this at the buttom:
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:542)
at java.lang.Integer.parseInt(Integer.java:615)
at app4pics1word.App4pics1word.cache(App4pics1word.java:127)
at app4pics1word.App4pics1word.<init>(App4pics1word.java:18)
at app4pics1word.App4pics1word.main(App4pics1word.java:146)
Java Result: 1
you can try this
public static void main(String[] args) {
try {
//something wrong happens here
}catch(Throwable e) {
e.printStackTrace();
main(args);
}
}
You should use exception handling instead of restarting the program. If you restart the program, the error will still be there and thus your program will keep on trying to run for eternity, always failing with the same exception.
You would like to catch your exception and make sure that the input is valid:
boolean okInput = false;
int x = -1;
String someData = "rr";
do {
try {
x = Integer.parseInt(someData); // try to parse
okInput = true;
} catch(NumberFormatException n) {
// Error, try again
okInput = false
someData = "2";
}
} while(!okInput); // Keep trying while input is not valid
// Here x is a valid number
This tutorial provides you good code in general of how exceptions work.
is this what you are looking for ?
public static void main(String [] args) {
boolean done = false;
do {
try {
writeSomeFile();
done = true;
}
catch (Exception ex)
{
System.out.println("Exception trapped "+ex)
}
} while (!done);
}
You can make it a loop that is broken only when the try block succeeds without an Exception:
public static void main(String[] args) {
while(true) {
try {
...
break; //at the end of try block
}
catch (SomeException e) {
//print error message here, or do whatever
}
}
//program continues here once try block gets through w/o exceptions
...
}
However, instead of having this in your main I recommend hiding this rather ugly structure inside a method.

unreported exception Exception; must be caught or declared to be thrown

There's two classes:
The main one (Corina.java) and the one that I am having issues with (Functions.java). Without complicating things too much, Corina.java calls a method in Functions.java, the method checks if a boolean is true or false and asks for authentication based on that, the code is very impartial at the moment, though I am using a phidgets RFID reader and copied a portion of one of their examples. but I get the following error in JCreator:
--------------------Configuration: Corina - JDK version 1.7.0_45 <Default> - <Default>--------------------
C:\Users\alexis.JKLSEMICOLON\Documents\JCreator LE\MyProjects\Corina\src\Functions.java:23: error: unreported exception Exception; must be caught or declared to be thrown
authenticateContinue();
^
First class code:
public class Corina {
public static void main(String[] args) {
Functions funtion = new Functions();
funtion.authenticateStart();
}
}
Second class code:
import com.phidgets.*;
import com.phidgets.event.*;
public class Functions {
public void authenticateStart() {
boolean authStatus = false;
System.out.println("The authentication status is currently: " + authStatus + ".");
if (authStatus) {
System.out.println("The applications is unlocked. Please wait.");
// applicationStart();
} else {
System.out.println("Please authenticate now by swiping one of the RFID tags allowed to unlock the program.");
authenticateContinue();
}
}
public void authenticateContinue() throws Exception {
RFIDPhidget rfid;
System.out.println(Phidget.getLibraryVersion());
rfid = new RFIDPhidget();
rfid.addAttachListener(new AttachListener() {
public void attached(AttachEvent ae) {
try {
((RFIDPhidget) ae.getSource()).setAntennaOn(true);
((RFIDPhidget) ae.getSource()).setLEDOn(true);
} catch (PhidgetException ex) {
}
System.out.println("attachment of " + ae);
}
});
rfid.addDetachListener(new DetachListener() {
public void detached(DetachEvent ae) {
System.out.println("detachment of " + ae);
}
});
rfid.addErrorListener(new ErrorListener() {
public void error(ErrorEvent ee) {
System.out.println("error event for " + ee);
}
});
rfid.addTagGainListener(new TagGainListener() {
public void tagGained(TagGainEvent oe) {
System.out.println(oe);
}
});
rfid.addTagLossListener(new TagLossListener() {
public void tagLost(TagLossEvent oe) {
System.out.println(oe);
}
});
rfid.addOutputChangeListener(new OutputChangeListener() {
public void outputChanged(OutputChangeEvent oe) {
System.out.println(oe);
}
});
rfid.openAny();
System.out.println("waiting for RFID attachment...");
rfid.waitForAttachment(1000);
System.out.println("Serial: " + rfid.getSerialNumber());
System.out.println("Outputs: " + rfid.getOutputCount());
System.out.println("Outputting events. Input to stop.");
System.in.read();
System.out.print("closing...");
rfid.close();
rfid = null;
System.out.println(" ok");
if (false) {
System.out.println("wait for finalization...");
System.gc();
}
}
}
any help would be appreciated. Ideally, I would like to just have the tag saved to a string, so if you would be knowledgeable on that, by all means.
Your problem is that authenticateStart calls authenticateContinue(), but you've flagged authenticateContinue as able to throw an Exception. That means that authenticateStart needs to be able to deal with that exception when it's thrown. You have a couple of options.
Put the call to authenticateContinue inside a try block, and deal with the exception in a catch block beneath it.
Change authenticateContinue so that it doesn't throw a checked exception.
Flag authenticateStart as able to throw an Exception. This will push the problem up into main, where you're calling authenticateStart.
No matter what you do, you'll have to deal with that exception somehow. The whole point of Java exception handling is that you can't just leave checked exceptions unhandled - you have to deal with them somehow.

Why do I get NoSuchElementException even though I am catching it in cucumber stepdefinition?

#When("^user clicks linkedin button of the first news item$")
public void user_clicks_linkedin_button_of_the_first_news_item()
{
try
{
firstSocialShareElement = driver.findElement(By.className("social-share-linkedin"));
if(firstSocialShareElement!=null && firstSocialShareElement.isDisplayed())
{
firstSocialShareElement.click();
}
}
catch(NoSuchElementException e)
{
}
}
It turns out it was a simple case of class name conflict.
Since i didn't specify the full qualified name of the exception as org.openqa.selenium. NoSuchElementException
It was considering it to be java.util. NoSuchElementException
and hence the exception was not getting caught.
Now the problem is resolved.
try
{
firstSocialShareElement = driver.findElement(By.className("social-share-linkedin"));
if(firstSocialShareElement!=null && firstSocialShareElement.isDisplayed())
{
firstSocialShareElement.click();
}
}
catch(org.openqa.selenium. NoSuchElementException e)
{
}

method flow control

I have a form that give Fname and Lname and Date and a method to write this information to a file.
If Fname or Lname contain digit, the program should display an error message and not run all below statements ,(like write to file and generate random number and...), and not exit.
since i dont know how to do like this, in my code i write if Fname or Lname have digit, exit !
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
setFName(jTextField1.getText());
if(havedigit(getFName())==true) {
System.exit(1);
}
setLName(jTextField2.getText());
if(havedigit(lastName)==true) {
System.exit(1);
}
WriteToFile(getFName());
WriteToFile(getLName());
setDate(Integer.parseInt(jTextField3.getText()));
WriteToFile(String.valueOf(getDate()));
Random rnd1=new Random();
Registration_Number=rnd1.nextInt(100);
setRegNum(Registration_Number);
WriteToFile(String.valueOf(getRegNum()));
jLabel6.setText(String.valueOf(getRegNum()));
}
catch(Exception e){
jLabel6.setText("Error!");
}
}
public boolean havedigit(String in){
for(int i=0;i<in.length();i++){
if(Character.isDigit(in.charAt(i))) return true;
}
return false;
}
please help!
That's why you need checked exceptions. Just throw SomeException instead of System.exit(1) and process it properly in block:
catch (SomeException e){
jLabel6.setText("Error!");
}
Don't think that catching all exceptions is a good idea.
Here's one way you could do it:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
setFName(jTextField1.getText());
setLName(jTextField2.getText());
boolean firstNameHasDigit = havedigit(getFName());
boolean lastNameHasDigit = havedigit(getLName());
if (firstNameHasDigit || lastNameHasDigit) {
jLabel6.setText("Names cannot contain digits");
}
else {
WriteToFile(getFName());
WriteToFile(getLName());
setDate(Integer.parseInt(jTextField3.getText()));
WriteToFile(String.valueOf(getDate()));
Random rnd1=new Random();
Registration_Number=rnd1.nextInt(100);
setRegNum(Registration_Number);
WriteToFile(String.valueOf(getRegNum()));
jLabel6.setText(String.valueOf(getRegNum()));
}
}
catch(Exception e){
jLabel6.setText("Error!");
}
}
public boolean havedigit(String in){
for(int i=0;i<in.length();i++){
if(Character.isDigit(in.charAt(i))) return true;
}
return false;
}
As a general rule, try to stay away from using System.exit() in GUI-driven applications. It'll just make the whole program quit, leaving the user wondering what happened. System.exit() is usually better suited for command line applications that want to provide an exit code to the shell and it's a parallel to the system exit calls available in most operating systems.
Try this:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
setFName(jTextField1.getText());
if(havedigit(getFName())) {
jLabel6.setText("First name error!");
return;
}
setLName(jTextField2.getText());
if(havedigit(lastName)) {
jLabel6.setText("Last name error!");
return;
}
WriteToFile(getFName());
WriteToFile(getLName());
setDate(Integer.parseInt(jTextField3.getText()));
WriteToFile(String.valueOf(getDate()));
Random rnd1=new Random();
Registration_Number=rnd1.nextInt(100);
setRegNum(Registration_Number);
WriteToFile(String.valueOf(getRegNum()));
jLabel6.setText(String.valueOf(getRegNum()));
}
catch(Exception e){
jLabel6.setText("Error!");
}
}
if(havedigit(getFName())==true) {
System.exit(1);
}
setLName(jTextField2.getText());
if(havedigit(lastName)==true) {
System.exit(1);
}
should be
if(havedigit(getFName())) {
JOptionPane.showMessageDialog(.....);
return; //get out of method, no need to continue
}
setLName(jTextField2.getText());
if(havedigit(lastName)) {
JOptionPane.showMessageDialog(.....);
return; //get out of method, no need to continue
}
Search on Google about how to use JOptionPane.showMessageDialog.
In your if statements, instead of
System.exit(1);
You should have something
throw new MyException("Error Text");
and then your catch should look like this:
catch(MyException e){
jLabel6.setText(e.getMessage());
}
where MyException extends Exception.

Telling a ThreadPoolExecutor when it should go ahead or not

I have to send a set of files to several computers through a certain port. The fact is that, each time that the method that sends the files is called, the destination data (address and port) is calculated. Therefore, using a loop that creates a thread for each method call, and surround the method call with a try-catch statement for a BindException to process the situation of the program trying to use a port which is already in use (different destination addresses may receive the message through the same port) telling the thread to wait some seconds and then restart to retry, and keep trying until the exception is not thrown (the shipping is successfully performed).
I didn't know why (although I could guess it when I first saw it), Netbeans warned me about that sleeping a Thread object inside a loop is not the best choice. Then I googled a bit for further information and found this link to another stackoverflow post, which looked so interesting (I had never heard of the ThreadPoolExecutor class). I've been reading both that link and the API in order to try to improve my program, but I'm not yet pretty sure about how am I supposed to apply that in my program. Could anybody give a helping hand on this please?
EDIT: The important code:
for (Iterator<String> it = ConnectionsPanel.list.getSelectedValuesList().iterator(); it.hasNext();) {
final String x = it.next();
new Thread() {
#Override
public void run() {
ConnectionsPanel.singleAddVideos(x);
}
}.start();
}
private static void singleAddVideos(String connName) {
String newVideosInfo = "";
for (Iterator<Video> it = ConnectionsPanel.videosToSend.iterator(); it.hasNext();) {
newVideosInfo = newVideosInfo.concat(it.next().toString());
}
try {
MassiveDesktopClient.sendMessage("hi", connName);
if (MassiveDesktopClient.receiveMessage(connName).matches("hello")) {
MassiveDesktopClient.sendMessage(newVideosInfo, connName);
}
} catch (BindException ex) {
MassiveDesktopClient.println("Attempted to use a port which is already being used. Waiting and retrying...", new Exception().getStackTrace()[0].getLineNumber());
try {
Thread.sleep(MassiveDesktopClient.PORT_BUSY_DELAY_SECONDS * 1000);
} catch (InterruptedException ex1) {
JOptionPane.showMessageDialog(null, ex1.toString(), "Error", JOptionPane.ERROR_MESSAGE);
}
ConnectionsPanel.singleAddVideos(connName);
return;
}
for (Iterator<Video> it = ConnectionsPanel.videosToSend.iterator(); it.hasNext();) {
try {
MassiveDesktopClient.sendFile(it.next().getAttribute("name"), connName);
} catch (BindException ex) {
MassiveDesktopClient.println("Attempted to use a port which is already being used. Waiting and retrying...", new Exception().getStackTrace()[0].getLineNumber());
try {
Thread.sleep(MassiveDesktopClient.PORT_BUSY_DELAY_SECONDS * 1000);
} catch (InterruptedException ex1) {
JOptionPane.showMessageDialog(null, ex1.toString(), "Error", JOptionPane.ERROR_MESSAGE);
}
ConnectionsPanel.singleAddVideos(connName);
return;
}
}
}
Your question is not very clear - I understand that you want to rerun your task until it succeeds (no BindException). To do that, you could:
try to run your code without catching the exception
capture the exception from the future
reschedule the task a bit later if it fails
A simplified code would be as below - add error messages and refine as needed:
public static void main(String[] args) throws Exception {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(corePoolSize);
final String x = "video";
Callable<Void> yourTask = new Callable<Void>() {
#Override
public Void call() throws BindException {
ConnectionsPanel.singleAddVideos(x);
return null;
}
};
Future f = scheduler.submit(yourTask);
boolean added = false; //it will retry until success
//you might use an int instead to retry
//n times only and avoid the risk of infinite loop
while (!added) {
try {
f.get();
added = true; //added set to true if no exception caught
} catch (ExecutionException e) {
if (e.getCause() instanceof BindException) {
scheduler.schedule(yourTask, 3, TimeUnit.SECONDS); //reschedule in 3 seconds
} else {
//another exception was thrown => handle it
}
}
}
}
public static class ConnectionsPanel {
private static void singleAddVideos(String connName) throws BindException {
String newVideosInfo = "";
for (Iterator<Video> it = ConnectionsPanel.videosToSend.iterator(); it.hasNext();) {
newVideosInfo = newVideosInfo.concat(it.next().toString());
}
MassiveDesktopClient.sendMessage("hi", connName);
if (MassiveDesktopClient.receiveMessage(connName).matches("hello")) {
MassiveDesktopClient.sendMessage(newVideosInfo, connName);
}
for (Iterator<Video> it = ConnectionsPanel.videosToSend.iterator(); it.hasNext();) {
MassiveDesktopClient.sendFile(it.next().getAttribute("name"), connName);
}
}
}

Categories