Thursday, March 13, 2014

Current Time Stamp

import java.text.SimpleDateFormat;
import java.util.Date;
 
public static String getCurrentTimeInstance() throws Exception {

String currentTimeInstance = null;

try {

Date today = Calendar.getInstance().getTime();

// Create our date "formatter" (the date format we want)
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss");

// Create a new String using the date format we want
currentTimeInstance = formatter.format(today);

} catch (Exception e) {
APPLICATION_LOGS.error(e);
}
return currentTimeInstance;
}
 
 (OR)
 
//Returns the current time when the method is called
   public String getCurrentTime(){
     DateFormat dateFormat =
         new SimpleDateFormat("HH:mm:ss:SSS");
     Date dt = new Date();
     return dateFormat.format(dt);    
   }
 }

Friday, February 7, 2014

Hover the Mouse on a menu and click on a dropdown menu option

public class HoverAndClickOnAMenu {
public static void main(String[] args) {

//initialise browser
WebDriver driver = new FirefoxDriver();
driver.get("http://www.ticketmaster.co.uk");

//locate the menu to hover over using its xpath
WebElement menu = driver.findElement(By.xpath("//*[@id='music']"));

//Initiate mouse action using Actions class
Actions builder = new Actions(driver); 

// move the mouse to the earlier identified menu option
builder.moveToElement(menu).build().perform();

// wait for max of 5 seconds before proceeding. This allows sub menu appears properly before trying to click on it
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id='subNav_music_menu']/tbody/tr[2]/td[1]/a[1]")));  // until this submenu is found

//identify menu option from the resulting menu display and click
WebElement menuOption = driver.findElement(By.xpath("//*[@id='subNav_music_menu']/tbody/tr[2]/td[1]/a[1]"));
menuOption.click();
}
}

public class HoverAndClickOnAMenu {
public static void main(String[] args) {

//initialise browser
WebDriver driver = new FirefoxDriver();
driver.get("http://www.ticketmaster.co.uk"); 

//locate the menu to hover over using its xpath
WebElement menu = driver.findElement(By.xpath("//*[@id='music']"));

//Initiate mouse action using Actions class
Actions builder = new Actions(driver);   

// move the mouse to the earlier identified menu option
builder.moveToElement(menu).build().perform();

// wait for max of 5 seconds before proceeding. This allows sub menu appears properly before trying to click on it
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id='subNav_music_menu']/tbody/tr[2]/td[1]/a[1]")));  // until this submenu is found

//identify menu option from the resulting menu display and click
WebElement menuOption = driver.findElement(By.xpath("//*[@id='subNav_music_menu']/tbody/tr[2]/td[1]/a[1]"));
menuOption.click();
}
} - See more at: http://www.logicandtricks.com/articles/hover-mouse-menu-and-click-resulting-dropdown-menu-option#sthash.XNT8wK5B.dpuf
public class HoverAndClickOnAMenu {
public static void main(String[] args) {

//initialise browser
WebDriver driver = new FirefoxDriver();
driver.get("http://www.ticketmaster.co.uk"); 

//locate the menu to hover over using its xpath
WebElement menu = driver.findElement(By.xpath("//*[@id='music']"));

//Initiate mouse action using Actions class
Actions builder = new Actions(driver);   

// move the mouse to the earlier identified menu option
builder.moveToElement(menu).build().perform();

// wait for max of 5 seconds before proceeding. This allows sub menu appears properly before trying to click on it
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id='subNav_music_menu']/tbody/tr[2]/td[1]/a[1]")));  // until this submenu is found

//identify menu option from the resulting menu display and click
WebElement menuOption = driver.findElement(By.xpath("//*[@id='subNav_music_menu']/tbody/tr[2]/td[1]/a[1]"));
menuOption.click();
}
} - See more at: http://www.logicandtricks.com/articles/hover-mouse-menu-and-click-resulting-dropdown-menu-option#sthash.XNT8wK5B.dpuf

Saturday, January 25, 2014

PostgresSQL Connection With Java

package exercise.qa.selenium;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.ResultSet; 
import java.sql.Statement;

public class PostgreSQLJDBC {
    static Connection con = null;
    static Statement stmt = null;
    static ResultSet rs = null;

    /*
     * Connecting To Database
     */
    public static void main(String[] arg) {

        System.out.println("-------- PostgreSQL "
                + "JDBC Connection Testing ------------");

        try {

            Class.forName("org.postgresql.Driver");

        } catch (ClassNotFoundException e) {

            System.out.println("Where is your PostgreSQL JDBC Driver? "
                    + "Include in your library path!");
            e.printStackTrace();
            return;

        }

        System.out.println("PostgreSQL JDBC Driver Registered!");

        try {

            con = DriverManager.getConnection(
                    "jdbc:postgresql://127.0.0.1:5432/testdb", "postgres",
                    "password");

        } catch (SQLException e) {
             e.printStackTrace();
             System.err.println(e.getClass().getName()+": "+e.getMessage());
             System.exit(0);

        }

        if (con != null) {
            System.out.println("You made it, take control your database now!");
        } else {
            System.out.println("Failed to make connection!");
        }
    }
   
    /*
     * Create a Table
     */
    public static void createTable(){
        try {
         stmt = con.createStatement();
         String sql = "CREATE TABLE COMPANY " +
                      "(ID INT PRIMARY KEY     NOT NULL," +
                      " NAME           TEXT    NOT NULL, " +
                      " AGE            INT     NOT NULL, " +
                      " ADDRESS        CHAR(50), " +
                      " SALARY         REAL)";
         stmt.executeUpdate(sql);
        } catch (SQLException e ) {
             System.err.println( e.getClass().getName()+": "+ e.getMessage() );
             System.exit(0);
           }finally {
        try{
            if (stmt != null) {
                stmt.close();
            }
            if (con != null) {
                con.close();
            }       
        }catch (SQLException e ) {
             System.err.println( e.getClass().getName()+": "+ e.getMessage() );
             System.exit(0);
           }
           }
    }

   
    /*
     * INSERT Operation
     */
   
    public static void insertRecords(){
        try {
        con.setAutoCommit(false);
        stmt = con.createStatement();
        String sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) "
              + "VALUES (1, 'Paul', 32, 'California', 20000.00 );";
        stmt.executeUpdate(sql);
        con.commit();
        }catch (Exception e) {
             System.err.println( e.getClass().getName()+": "+ e.getMessage() );
             System.exit(0);
          }finally {
              try{
                if (stmt != null) {
                    stmt.close();
                }
                if (con != null) {
                    con.close();
                }       
            }catch (SQLException e ) {
                 System.err.println( e.getClass().getName()+": "+ e.getMessage() );
                 System.exit(0);
               }
          }
    }
   
    /*
     * SELECT Operation
     */
   
    public static void selectRecords(){
        try {
            con.setAutoCommit(false);
             stmt = con.createStatement();
             rs = stmt.executeQuery( "SELECT * FROM COMPANY;" );
             while ( rs.next() ) {
                int id = rs.getInt("id");
                String  name = rs.getString("name");
                int age  = rs.getInt("age");
                String  address = rs.getString("address");
                float salary = rs.getFloat("salary");
                System.out.println( "ID = " + id );
                System.out.println( "NAME = " + name );
                System.out.println( "AGE = " + age );
                System.out.println( "ADDRESS = " + address );
                System.out.println( "SALARY = " + salary );
                System.out.println();
             }
           } catch ( Exception e ) {
             System.err.println( e.getClass().getName()+": "+ e.getMessage() );
             System.exit(0);
           }finally {
                  try{
                       if (rs != null) {
                          rs.close();
                        }
                    if (stmt != null) {
                        stmt.close();
                    }
                    if (con != null) {
                        con.close();
                    }       
                }catch (SQLException e ) {
                     System.err.println( e.getClass().getName()+": "+ e.getMessage() );
                     System.exit(0);
                   }
              }
    }
   
    /*
     * UPDATE Operation
     */
   
    public static void updateRecords(){
        try {
            con.setAutoCommit(false);
             stmt = con.createStatement();
             String sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1;";
             stmt.executeUpdate(sql);
             con.commit();
             rs = stmt.executeQuery( "SELECT * FROM COMPANY;" );
             while ( rs.next() ) {
                int id = rs.getInt("id");
                String  name = rs.getString("name");
                int age  = rs.getInt("age");
                String  address = rs.getString("address");
                float salary = rs.getFloat("salary");
                System.out.println( "ID = " + id );
                System.out.println( "NAME = " + name );
                System.out.println( "AGE = " + age );
                System.out.println( "ADDRESS = " + address );
                System.out.println( "SALARY = " + salary );
                System.out.println();
             }
           } catch ( Exception e ) {
             System.err.println( e.getClass().getName()+": "+ e.getMessage() );
             System.exit(0);
           }finally {
                  try{
                       if (rs != null) {
                          rs.close();
                        }
                    if (stmt != null) {
                        stmt.close();
                    }
                    if (con != null) {
                        con.close();
                    }       
                }catch (SQLException e ) {
                     System.err.println( e.getClass().getName()+": "+ e.getMessage() );
                     System.exit(0);
                   }
              }
    }
   
    /*
     * DELETE Operation
     */
   
    public static void deleteRecords(){
        try {
            con.setAutoCommit(false);
             stmt = con.createStatement();
             String sql = "DELETE from COMPANY where ID=2;";
             stmt.executeUpdate(sql);
             con.commit();
             rs = stmt.executeQuery( "SELECT * FROM COMPANY;" );
             while ( rs.next() ) {
                int id = rs.getInt("id");
                String  name = rs.getString("name");
                int age  = rs.getInt("age");
                String  address = rs.getString("address");
                float salary = rs.getFloat("salary");
                System.out.println( "ID = " + id );
                System.out.println( "NAME = " + name );
                System.out.println( "AGE = " + age );
                System.out.println( "ADDRESS = " + address );
                System.out.println( "SALARY = " + salary );
                System.out.println();
             }
           } catch ( Exception e ) {
             System.err.println( e.getClass().getName()+": "+ e.getMessage() );
             System.exit(0);
           }finally {
                  try{
                       if (rs != null) {
                          rs.close();
                        }
                    if (stmt != null) {
                        stmt.close();
                    }
                    if (con != null) {
                        con.close();
                    }       
                }catch (SQLException e ) {
                     System.err.println( e.getClass().getName()+": "+ e.getMessage() );
                     System.exit(0);
                   }
              }
    }
   
}//End of the Class

   

Wednesday, December 11, 2013

Confirm text is displayed in webpage

public boolean isTextPresent(String text) {
    List<WebElement> foundElements = driver.findElements(By.xpath 
("//*[contains(text(), '" + text + "')]"));
    return foundElements.size() > 0;
}

Tuesday, December 3, 2013

Handling Web Popup dialog boxes and Windows Authentication popup

Alert alert = driver.switchTo().alert();
      alert.accept();
(OR)
            alert.dismiss();
(OR)
            alert.read();
(OR)
     alert.getText();
(OR)
driver.switchTo().activeElement();
             
(OR)
 
public boolean isAlertPresent() {
 
           boolean presentFlag = false;
           String alterTitle = null;
 
           try {
 
                // Check the presence of alert
                Alert alert = driver.switchTo().alert();
                // Alert present; set the flag
                return true;
               
           } catch (NoAlertPresentException e) {
                return false;    
    }
          
       }
(OR)
public boolean isAlertPresent(int timeoutSec) {
            WebDriverWait wait = new WebDriverWait(driver, timeoutSec);
             try {
                 wait.until(ExpectedConditions.alertIsPresent());
                 return true;
             } catch (TimeoutException e) {
                 return false;
             }
       }

(OR)
public static void  handleAlert(WebDriver driver, boolean acceptAlert) {
        try {
            Alert alert = driver.switchTo().alert();
            if (acceptAlert) {
                alert.accept();
            } else {
                alert.dismiss();
            }
           
        } catch (NoAlertPresentException e) {
            
        }
    }


Handle Windows Authentication popup using Selenium Webdriver:

public static void handler() throws IOException
{
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
Runtime.getRuntime().exec("D:\\Scripts\\AutoITScript\\HandleAuthentication.exe");
  driver.get("https://www.engprod-charter.net/");
 }
 
AutoIT Script:
WinWaitActive("Authentication Required","","10")
If WinExists("Authentication Required") Then
Send("username{TAB}")
Send("Password{Enter}")
EndIf’
 
 
 By passing UsenName and Password in the URl:
public static final String TEST_ENVIRONMENT = "the-site.com";

public void login(String uname, String pwd){
String URL = "http://" + uname + ":" + pwd + "@" + TEST_ENVIRONMENT;
driver.get(URL);
Thread.sleep(5000);
}

Robot script:
public void login() throws Exception {

//wait – increase this wait period if required
Thread.sleep(5000);

//create robot for keyboard operations
Robot rb = new Robot();

//Enter user name by ctrl-v
StringSelection username = new StringSelection(“username”);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(username, null);
rb.keyPress(KeyEvent.VK_CONTROL);
rb.keyPress(KeyEvent.VK_V);
rb.keyRelease(KeyEvent.VK_V);
rb.keyRelease(KeyEvent.VK_CONTROL);

//tab to password entry field
rb.keyPress(KeyEvent.VK_TAB);
rb.keyRelease(KeyEvent.VK_TAB);
Thread.sleep(2000);

//Enter password by ctrl-v
StringSelection pwd = new StringSelection(“password”);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(pwd, null);
rb.keyPress(KeyEvent.VK_CONTROL);
rb.keyPress(KeyEvent.VK_V);
rb.keyRelease(KeyEvent.VK_V);
rb.keyRelease(KeyEvent.VK_CONTROL);

//press enter
rb.keyPress(KeyEvent.VK_ENTER);
rb.keyRelease(KeyEvent.VK_ENTER);

//wait
Thread.sleep(5000);
}
 

Friday, August 30, 2013

How to type some text in hidden field in WebDriver



First of all you have to change the value of type attribute as text from hidden. The following code using javascript would work for that:
EX:
jse.executeScript("document.getElementsByName('body')[0].setAttribute('type', 'text');");

Now, you are able to type on that text by using WebDriver. So, the overall code for typing with WebDriver using Java and Javascript as follows:


EX:
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("document.getElementsByName('body')[0].setAttribute('type', 'text');");
driver.findElement(By.xpath("//input[@name='body']")).clear();
driver.findElement(By.xpath("//input[@name='body']")).sendKeys("Ripon: body text");