Comparing identical strings using String.equals is found getting skipped - java

Below is my code
for(int j=0;j<6;j++){
//checking each deal
dealname=driver.findElement(By.id("MainContent_dtlstAllDeals_lblDealTitle_"+j)).getText();
// System.out.println(dealname);
String result[]=dealname.split("\\.");
String resultTitle=result[0];
//System.out.println(resultTitle);
String splitDealname=DealTitle.substring(0,resultTitle.length());
if(splitDealname.equals(resultTitle)){
System.out.println("***whoooooo you got it********"+j+"position"+"in"+i+"page");
//click on view deal button
driver.findElement(By.id("MainContent_dtlstAllDeals_lbtnView_"+j)).click();
Thread.sleep(5000);
//System.out.println(driver.findElement(By.id("MainContent_lblDealTitle")).getText());
String name=driver.findElement(By.id("MainContent_lblDealTitle")).getText();
//verify selected deal is correct
System.out.println(name);
//Thread.sleep(5000);
try {
if (name.equals(DealTitle)) {
System.out.println("whoos...verified");
}
/*
String statuss=veifyTitle("");
if(statuss.equals("success")){
{
System.out.println("whoos...verified");
//do buying process
}
}
else{}*/
} catch (Exception e) {
// TODO: handle exception
System.out.println(e);
}
}
Even though variables DealTitle and name contain same long string as below , that above code is not working.I have put the code in for loop , but when the 'if' condition is run it goes to next iteration .I found it while debugging
Detailed Interior Cleaning + Exterior Car Wash (External Foam Wash, Shampooing, Conditioning, Engine Room Wash, Tyre Polishing) Using AUTOGLYM Brand Products for Just Rs. 399 from Hasten Auto, Vennala (76% OFF)-pramod
Pls help.

I got issue solved by using replace all method
String excelTitle= DealTitle.replaceAll("[^\\w\\s\\-_]", "");
String pageTitle=name.replaceAll("[^\\w\\s\\-_]", "");
if(excelTitle.compareTo(pageTitle)==0){
System.out.println("ok strings are same");
}
Or you can use name.replaceAll("[^a-zA-Z]", "")

Related

always getting 6a82 and 6d00 for reading visa emv card

i am reading data from visa card but always getting response 6a82 and 6d00 for PSE.
I am using smartcardio and following are the commands
Select PSE:
00A404000E315041592E5359532E444446303100
Processing code:
80A8000002830000
Below code works fine for paypak (a Pakistan payment card claiming EMV compatibility) but for visa its not working.
startCardConnection("0");
String commandVisa = "00A4040007A000000003101000";
String command_PSE = "00A404000E315041592E5359532E444446303100";
String command_getProcessingOptionsVISA = "80A8000002830000";
String response;
response = executeCardCommand(command_PSE);
response = executeCardCommand(commandVisa);
readCardRecords(2);
response = executeCardCommand(command_getProcessingOptionsVISA);
response = executeCardCommand("80AE8000210000000000000000000000000586000000000005861802020000E44E4B11040001");
public static String executeCardCommand(String command) {
if (transmissionTrace)
System.out.println("SYS: Executing card command:" + command);
capdu = makeCommandAPDU(command);
TLV tagsList;
try {
if (card == null) {
System.out.println("SYS: ERR: Card not present/not responding!");
return null;
}
responsedAPDU = card.getBasicChannel().transmit(capdu);
showRes(responsedAPDU.getBytes());
tagsList = new TLV(responsedAPDU.getBytes());
allTagsTLV.getChildren().add(tagsList);
System.out.println(">>>>>>>>>>>>" + responsedAPDU.toString());
} catch (CardException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (TLVException e1) {
// TODO Auto-generated catch block
System.out.println("SYS: NO tags response. May be correct if not expecting tags.");
}
return allTagsTLV.getJson();
}
Support for PSE for contact is optional - both for cards as well as for terminals. From the terminal/kernel perspective only LoA (List of AIDs) method is obligatory. As described in detail by EMV Book 1 chapter 12.3, when PSE is missing (status word 6A82), terminal should build candidate list using List of AIDs method basing on its configuration. I don't know when you are getting 6D00, but you don't perform application selection correctly, so I guess you are firing the commands like GPO and GenAC with no application selected. The code you are quoting is very wrong - it does not handle any errors, does not select application correctly, it does not check for PDOL presence, does not read records with CDOL1, does not build DOLs. Quite honestly it may work by coincidence only.

else statement still runs even when else if condtions pass

I'm having issues getting my if else statement to work correctly, here I have a login in form that uses values from a database. The statement for the Employee role works fine but even if the else if statement passes the else statement still runs.
If it helps the dialog box appears twice if the Customer statement passes and three time if the else runs by itself. I apologize if my code format is off I'm new at posting code here.
private void jBtnLoginActionPerformed(java.awt.event.ActionEvent evt) {
// action performed when the login button is pressed
// variables that will contain the row entries to the login data base (user name)
String userNameDb = "";
roleDb = rs.getString("role");
//database connection code
try
{
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("//database directory");
st=con.createStatement();
//selects entries from the userName password and role row from the user table
rs=st.executeQuery("Select userName, role From tblUser ;");
//loops through the table entires
while(rs.next())
{
//assigns database entry to variables
userNameDb = rs.getString("userName");
roleDb = rs.getString("role");
if (jTxtUserName.getText().equals(userNameDb) && roleDb.equals("Customer"))
{
//switch forms
break;
}
//if the users input and role match the data base for an customer send them to the selection form
else if (jTxtUserName.getText().equals(userNameDb) && roleDb.equals("Customer"))
{
//switch forms
break;
}
else
{
JOptionPane.showMessageDialog(null, "Login failed");
}
}
}
catch(Exception ex)
{
System.out.println("" + ex);
}
}
}
The problem is that your while loop is coded wrong as your "Login failed" JOptionPane else block shouldn't be within the while loop. Instead declare a boolean value before the loop, set it to false, check if the username/password are found within the that loop, and if so, set the boolean to true. Then after the loop check the boolean value, and if false, show the error message.
To see why, use a debugger to run through the code to see why it's behaving the way it's behaving. More importantly, learn the "rubber duck" debugging technique where you walk through your code mentally or on paper, telling the duck what each line of code should be doing.
To illustrate, your code is behaving something like the code below where a boolean array is mimicking your password username check. Of course, you'd be using a while loop, not a for loop, but this was used here to make the example simpler:
private someActionPerformedMethod() {
// boolean representing when the username/password test is OK
boolean[] loopItems = { false, false, false, true, false };
for (boolean loopItem : loopItems) {
if (loopItem) {
break;
} else {
JOptionPane.showMessageDialog(null, "Login failed");
}
}
}
Assume that the password/username only matches on the 4th try (forth item is true), then for each failed check, the JOptionPane will show a failed login. What you want instead is something like:
private someActionPerformedMethod() {
// boolean representing when the username/password test is OK
boolean[] loopItems = { false, false, false, true, false };
boolean userFound = false;
// you'll of course be using a while loop here
for (boolean loopItem : loopItems) {
if (loopItem) {
userFound = true;
// do something with user data
break;
}
}
if (!userFound) {
JOptionPane.showMessageDialog(null, "Login failed");
}
}

Selenium: how to write if condition when there is no element for some xpath

Below is the code and question:
if(result.findElement(By.xpath(".//*[#class='s-item-container']/div[4]/span/a/i")).getText().equals("Lightning Deal"))
After we search any product on Amazon, we can also see the "Lighting Deal" option on some products. Now here I am trying to check if the lighting deal option is present or not. If it is present then condition is true and everything is okay. But if there is no lighting deal, then this gives the error NoSuchElementException because then div[4]/span/a/i doesn't exist. This div[4]/span/a/i comes into life only when there is some lighting deal.
Please suggest me how to write this if condition.
Complete Code:
//All the products after searching in List
List<WebElement> resultsList = driver.findElements(By.xpath(".//*[starts-with(#id, 'result_')]"));
for(WebElement result:resultsList)
{
System.out.println("Name of the product:"+result.findElement(By.tagName("h2")).getText());
System.out.println("Brand: "+result.findElement(By.xpath(".//*[#class='s-item-container']/div[3]/div[2]/span[2]")).getText());
if(result.findElement(By.xpath(".//*[#class='s-item-container']/div[4]/span/a/i")).getText().equals("Lightning Deal"))
{
String sp =result.findElement(By.xpath(".//*[#class='s-item-container']/div[5]/div[1]/a/span[2]")).getText();
System.out.println("Selling Price: "+sp);
}
else
{
System.out.println("Selling Price:"+result.findElement(By.xpath(".//*[#class='s-item-container']/div[4]/div[1]/a/span[2]")).getText());
}
}
you can check the element is present on page before getting text
for(WebElement result:resultsList)
{
System.out.println("Name of the
product:"+result.findElement(By.tagName("h2")).getText());
System.out.println("Brand: "+result.findElement(By.xpath(".//*[#class='s-
item-container']/div[3]/div[2]/span[2]")).getText());
if(result.findElements(By.xpath(".//*[#class='s-item-
container']/div[4]/span/a/i")).size() != 0
&& result.findElement(By.xpath(".//*[#class='s-item-
container']/div[4]/span/a/i")).getText().equals("Lightning Deal"))
{
String sp =result.findElement(By.xpath(".//*[#class='s-item-
container']/div[5]/div[1]/a/span[2]")).getText();
System.out.println("Selling Price: "+sp);
}
else
{
System.out.println("Selling Price:"+result.findElement(By.xpath(".//*
[#class='s-item-container']/div[4]/div[1]/a/span[2]")).getText());
}
}
This is what you need to do
List<WebElement> deals = result.findElements(By.xpath(".//*[#class='s-item-container']/div[4]/span/a/i"));
if(deals.size() > 0)
{
if(deals.get(0).getText().equals("Lightning Deal"))
{
String sp =result.findElement(By.xpath(".//*[#class='s-item-container']/div[5]/div[1]/a/span[2]")).getText();
System.out.println("Selling Price: "+sp);
}
else
{
System.out.println("Selling Price:"+result.findElement(By.xpath(".//*[#class='s-item-container']/div[4]/div[1]/a/span[2]")).getText());
}
}
Hope this helps
You need to enclose the if Statement in Try catch block
Enclose your if condition in try block . So if your element is there then you will be able to do your action in if condition.
If there is no such xpath then it will throw exception which will be handle under catch block so just write you else part under catch block
Refer Below code:
//All the products after searching in List
List<WebElement> resultsList = driver.findElements(By.xpath(".//*[starts-with(#id, 'result_')]"));
for(WebElement result:resultsList)
{
System.out.println("Name of the product:"+result.findElement(By.tagName("h2")).getText());
System.out.println("Brand: "+result.findElement(By.xpath(".//*[#class='s-item-container']/div[3]/div[2]/span[2]")).getText());
try
{
if(result.findElement(By.xpath(".//*[#class='s-item-container']/div[4]/span/a/i")).getText().equals("Lightning Deal"))
{
String sp =result.findElement(By.xpath(".//*[#class='s-item-container']/div[5]/div[1]/a/span[2]")).getText();
System.out.println("Selling Price: "+sp);
}
}
catch(Exception e)
{
System.out.println("Selling Price:"+result.findElement(By.xpath(".//*[#class='s-item-container']/div[4]/div[1]/a/span[2]")).getText());
}
}
This is one of my favorite hack. Basically the question is regarding, to check the element availability or not in the given page. findByElements method comes to action now. Below is the code.
if(driver.findElements(ByXpath("XPATH_HERE")).size>0)
{
//DO THE STUFF YOU NEED TO DO IF THE ELEMENT EXISTS
}
The statements inside the if block will be executed only there exists the element defined otherwise not. Hope this helps you.
Thanks.

AssertTrue in try/catch

Please what exactly am i doing wrong.
I have checked and checked but all to no avail.
I have also checked previous code but I am not getting an error so my code works fine but just slight error somewhere.
The code is running fine and assertTrue is behaving as expected but when I put it in the try/catch, I only get the log in the catch block, even when text was found.
I believe that if the assertTrue found the text, it should go to the next line of code in the try block and pass the test rather than the catch block. Don't get me wrong, I am not getting any error just that it's printing out the wrong message.
Code below including print out message in console.
public boolean verifyTextPresent(String value) throws Exception {
Thread.sleep(5000);
try{
boolean txtFound = driver.getPageSource().contains(value);
log.log(value + " : text Found, .......continue");
return txtFound;
}catch(Exception e)
{
log.log(value + " :NOT Found, check element again ot Contact developer.");
return false;
}
}
public static void verifySignOutBtn() throws Exception
{
log.header("VERIFY IF SIGN_OUT EXIST AND CLICKABLE.........");
callMethod.myAccountPageNative(CONSTANTElements.SIGN_IN_LINK);
Thread.sleep(2000);
log.header("LOCATE SIGN_OUT BTN, AND CLICK ......");
callMethod.elementPresent_Click(By.cssSelector(CONSTANTElements.SIGN_OUT_BTN));
Thread.sleep(4000);
log.header("VERIFY SIGN_OUT NAVIGATES TO HOME PAGE WHEN CLICKED......");
try{
Assert.assertTrue(callMethod.verifyTextPresent("SIGN IN"), "SIGN IN");
log.log("User Successfully Signed Out.......");
log.log("Test Passed!...");
//callMethod.close();
}
catch(Throwable e)
{
log.log("User NOT Successfully Signed Out.... Contact developer.");
log.log("Test Failed!...");
//callMethod.close();
}
callMethod.close();
}
}
Msg in console:
SIGN IN : text Found, .......continue
User NOT Successfully Signed Out.... Contact developer.
Test Failed!...
The confusing part is that why is it printing out the catch block instead of the next line in the try block?
Shouldn't it be the other way around?
Assert.assertTrue("Message if it is false", callMethod.verifyTextPresent("SIGN IN"));
The only possible explanation is that verifyTextPresent(String value) returns false (you never actually check the value of boolean txtFound) and assertTrue fails (throwing an AssertionError which is not handled well in your catch block). To find out, replace this
log.log(value + " : text Found, .......continue");
for example with this line
log.log(value + " : text Found, ......." + txtFound);
or just print the stacktrace in catch block.

LDAP Not processing showing SchemaViolationException

I am having a LDAP Queue which process a object class.I cant find the exact location why it is giving the exception. The objclass is a concadenation string with pipe symbol. Any program coding to find the exact location in which concadination part is going to the Exception?.Please Assist.
try {
Attributes objClass = null;
try {
objClass = getObjClass(LdapInfo.PER_ID, person.perId);
} catch (NamingException e)
{
DCXError.myInstance().writeError("LdapUpdaterConnection: " + e.getMessage());
}
NamingEnumeration oc = objClass.get("objectclass").getAll();
String baseObjClass = null;
while (oc.hasMoreElements()) {
baseObjClass = (String) oc.nextElement();
if (baseObjClass.equalsIgnoreCase(LdapInfo.NON_EMPLOYEE_PERSON)
|| baseObjClass.equalsIgnoreCase("N/A")||
baseObjClass.equalsIgnoreCase(LdapInfo.EMPLOYEE_PERSON))
break;
}
} catch (SchemaViolationException e4) {
DCXError.myInstance().writeError(
"LdapUpdaterConnection:doUpdate SchemaViolationException "+ e4.getExplanation());
DCXError.myInstance().writeError("LdapUpdaterConnection:update persID = " + personId);
return (LdapUpdaterConnection.BAD_DATA);
}
You can't find the exact location only because you haven't logged the stack trace. You would also need to reformat your code so that each statement is on a separate line to make any use of that information. You should also use variable names that actually correspond to the content.
This is really terrible code.
It's also hard to see why you are doing all this in the first place. A decent query filter would do all that for you far more simply.

Categories