Wednesday, March 13, 2013

WebDriver Java code for testing

package prognocis_pkg;


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;


import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


class CommonActions{
    public static WebElement element;
    public static WebDriver driver=new InternetExplorerDriver();
    public static String alertText="";
   
    public void OpenURL(String url) throws InterruptedException{
        driver.get(url);
        synchronized(driver){
            driver.wait(5000);
            }
        System.out.println("Current URL: "+driver.getCurrentUrl());
    }
   
    public static void initElem(String elem, String by){
        if(by.equals("id"))
            element=driver.findElement(By.id(elem));
        else if(by.equals("xpath"))
            element=driver.findElement(By.xpath(elem));
        else if(by.equals("name"))
            element=driver.findElement(By.name(elem));
        else if(by.equals("css"))
            element=driver.findElement(By.cssSelector(elem));
        else if(by.equals("tag"))
            element=driver.findElement(By.tagName(elem));
        else if(by.equals("link"))
            element=driver.findElement(By.linkText(elem));
        else if(by.equals("partialLink"))
            element=driver.findElement(By.partialLinkText(elem));
        else if(by.equals("class"))
            element=driver.findElement(By.className(elem));
       
        System.out.println("Element "+element.getAttribute("id")+" "+element.getAttribute("name")+" initialized.");
        return;
    }
   
    public void Click(String elem, String by)throws InterruptedException{       
        initElem(elem, by);
        System.out.println(element.getAttribute("id")+" clicking.");
        element.click();   
        synchronized(driver){
            driver.wait(8000);
            }
    }
   
    public void ClickAndHold(String elem, String by) throws InterruptedException{
        initElem(elem, by);
        new Actions(driver).clickAndHold(element).perform();
        synchronized(driver){
            driver.wait(2000);
            }
    }
   
    public void Release(String elem, String by) throws InterruptedException{
        initElem(elem, by);
        new Actions(driver).release(element).perform();
        synchronized(driver){
            driver.wait(5000);
            }
    }
   
    public void SetText(String elem, String by, String text)throws InterruptedException{
        initElem(elem, by);
        element.sendKeys(text);
        synchronized(driver){
            driver.wait(5000);
            }
        System.out.println("Entered "+text+" in element "+element.getAttribute("id"));
    }
   
    public void MouseOver(String elem, String by)throws InterruptedException{
        initElem(elem, by);       
        new Actions(driver).moveToElement(element).build().perform();
        synchronized(driver){
            driver.wait(5000);
            }
        System.out.println("MouseHovered on element "+element.getAttribute("id"));
    }
   
    public void SwitchToFrame(String frameName)throws InterruptedException{
        driver.switchTo().frame(frameName);
        synchronized(driver){
            driver.wait(10000);
            }
        System.out.println("Switched to Frame: "+frameName);
    }
   
    public void SwitchToWindow(String winTitle)throws InterruptedException{
        String parentWinID = driver.getWindowHandle();
        Set<String> winIDs = driver.getWindowHandles();
               
        for(String winID : winIDs){
            if(driver.switchTo().window(winID).getTitle().equals(winTitle)){
                driver.switchTo().window(winID);
            }else{
                driver.switchTo().window(parentWinID);
            }
        }
       
        synchronized(driver){
            driver.wait(10000);
            }
       
        System.out.println("Switched to window: "+driver.getTitle());
    }
   
    public void Select(String elem, String by, String selectOption) throws InterruptedException{
        initElem(elem, by);   
        List<WebElement> optionsDoc = element.findElements(By.tagName("option"));
       
        for (WebElement option : optionsDoc) {
            if(selectOption.equals(option.getText()))
                option.click();
        }
       
        synchronized(driver){
            driver.wait(5000);
            }
    }
   
    public String SwitchToAlert() throws InterruptedException{
        Alert alert = driver.switchTo().alert();   
        alertText = alert.getText();
        System.out.println(alertText);
        synchronized(driver){
            driver.wait(1000);
            }
        alert.accept();
        return alertText;
    }
   
    public int CountOfElements(String xpathVal){
        List<WebElement> lstElems = driver.findElements(By.xpath(xpathVal));
        System.out.println(lstElems.size());
        return lstElems.size();
    }
   
    public String GetAttributeValue(String elem, String by, String attribute){
        initElem(elem, by);
        String attributeValue = "";
       
        if(attribute.equals("text")){
             attributeValue=element.getText();
        }else{       
        attributeValue = element.getAttribute(attribute);
        }
       
        System.out.println("attributeValue: "+attributeValue);
        return attributeValue;
    }
   
    public boolean VerifyExistence(String elem, String by) throws InterruptedException{
        initElem(elem, by);
        try{
            new Actions(driver).moveToElement(element).build().perform();
            synchronized(driver){
                driver.wait(1000);
                }
        }catch(Exception e){
            return false;
        }
        return true;
    }
   
    public String XMLreader(String xmlPath, String elementName)
    {
        String elementValue = null;
        try
        {
            File file = new File(xmlPath);
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document =  db.parse(file);
            document.getDocumentElement().normalize();
            NodeList node = document.getElementsByTagName("TestData");
           
            for (int i = 0; i < node.getLength(); i++)
            {
                Node currentNode = node.item(i);
                if (currentNode.getNodeType() == Node.ELEMENT_NODE)
                {
                    Element elemnt = (Element) currentNode;
                    NodeList emailElemntList = elemnt.getElementsByTagName(elementName);
                    Element logindetails = (Element) emailElemntList.item(0);
                    NodeList mailServer1 = logindetails.getChildNodes();
                    elementValue =((Node)mailServer1.item(0)).getNodeValue();
                }
            }
        }
        catch(Exception e)
        {
            System.out.println("The Element Name " + elementName + " is not present.");
            e.printStackTrace();
        }
       
        return elementValue;
    }
   
    public void WriteLog(String logFileName, String str){   
        File file = new File("D:\\Selenium\\"+logFileName);
       
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter("D:\\Selenium\\"+logFileName,true);
            BufferedWriter out = new BufferedWriter(fw);
            out.append(str);
        //    out.write(str);
            out.close();
        } catch (IOException e) {
            System.err.println("Error: " + e.getMessage());           
            e.printStackTrace();           
        }
    }
}
class CommonTasks{
   
    public void Login(CommonActions objCA) throws InterruptedException{
        objCA.OpenURL("https://www.dummyUrl.com");
        objCA.SetText("username", "id", "user1");
        objCA.SetText("password", "id", "pass@123");
        objCA.Click("//button[@type='submit' and @class='button']", "xpath");       
    }
   
    public void GoToHomePg(CommonActions objCA) throws InterruptedException{
        objCA.SwitchToWindow("WindowTitle1");
        objCA.SwitchToFrame("topFrame");
        objCA.MouseOver("//img[@name=,'home')]", "xpath");
        objCA.Click("//img[@name=,'home')]", "xpath");
    }
   
    public void Navigate_Menu_Submenu(CommonActions objCA, String menu, String submenu) throws InterruptedException{
        objCA.SwitchToWindow("WindowTitle1");
        objCA.SwitchToFrame("topFrame");
        objCA.MouseOver("//img[@name='"+menu+"']", "xpath");
        objCA.Click("//span[contains(.,'"+submenu+"')]", "xpath");
    }
   
    public void ClickTimeSlot(CommonActions objCA, String KeyHrSlot, String KeyMinSlot, String AmOrPm) throws InterruptedException{       
        objCA.Click("//td[@class='apptschbg']//tr/td[text()='"+AmOrPm
                +"']//following::td[text()='"+KeyHrSlot
                +"']//following::tr//following::td[text()='"+KeyMinSlot+"']"
                ,"xpath");
    }
   
    public void ScheduleAppt(CommonActions objCA, String patLName, String patFName) throws InterruptedException{
        objCA.SwitchToWindow("Appointment Schedule");
        objCA.SwitchToFrame("ifViewdoc");
        objCA.SwitchToFrame("mainFrame");       
        objCA.SetText("PatientName", "id", patLName+" "+patFName);
        objCA.MouseOver("ok", "id");
        objCA.ClickAndHold("ok", "id");
        objCA.Release("ok", "id");
    }
   
    public String CurrentDateInFormat(String dtFormat){
        DateFormat dateFormat= new SimpleDateFormat();
        Date todaysDate= new Date();
        String dateString= dateFormat.format(todaysDate);
        return dateString;
    }
   
    public void MassSchedule(CommonActions objCA, String patLName, String patFName) throws InterruptedException{
        objCA.SwitchToWindow("WindowTitle1");
        objCA.SwitchToFrame("SchedulerFrame");
        objCA.Click("//input[@title='Mass Scheduling']", "xpath");
       
        objCA.SwitchToWindow("Mass Scheduling");
        objCA.SwitchToFrame("ifViewdoc");
        objCA.SwitchToFrame("mainFrame");
        objCA.Click("cbSelectAll", "id");
        boolean patExists = objCA.VerifyExistence("//td[text()='"+patLName+", "+patFName+"']", "xpath");
        String exists = patExists ? "Patient "+patLName+", "+patFName+" exists." : "Patient "+patLName+", "+patFName+" does not exist." ;
        System.out.println(exists);
        objCA.MouseOver("//table[@id='apptData']//td[contains(text(),'"+patLName+", "+patFName+"')]//preceding::td[2]/input//following::td[1]/input","xpath");
        objCA.Click("//table[@id='apptData']//td[contains(text(),'"+patLName+", "+patFName+"')]//preceding::td[2]/input//following::td[1]/input","xpath");
        objCA.Click("//input[@title='Calendar']", "xpath");
        int days=1;
        objCA.MouseOver("//span/div/div[2]/div/div[@class='boxMainCellsContainer']/div[@isToday='1']/following-sibling::div["+days+"]", "xpath");
        objCA.Click("//span/div/div[2]/div/div[@class='boxMainCellsContainer']/div[@isToday='1']/following-sibling::div["+days+"]", "xpath");
        objCA.MouseOver("ok", "id");
        objCA.ClickAndHold("ok", "id");
        objCA.Release("ok", "id");
    }
   
    public String DateAdd(String dateString, int days) throws ParseException{
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
        Calendar c = Calendar.getInstance();
        c.setTime(sdf.parse(dateString));
        c.add(Calendar.DATE, days); 
        String tomorrowsDate = sdf.format(c.getTime());
        return tomorrowsDate;
    }
   
    public void LogOut(CommonActions objCA) throws InterruptedException{
        objCA.SwitchToWindow("WindowTitle1");
        objCA.SwitchToFrame("topFrame");
        objCA.Click("//a/img[@name='logout']", "xpath");
    }
}


public class MassSch {   
   
    @SuppressWarnings("deprecation")
    public static void main(String[] args) {
        try{
        CommonActions objCA = new CommonActions();
        CommonTasks objTask = new CommonTasks();
       
        objTask.Login(objCA);
        objTask.Navigate_Menu_Submenu(objCA, "appmnt", "Schedule");               
       
        objCA.SwitchToFrame("SchedulerFrame");
        String SelectedDoctor="JohnDsouza";
        String SelectedLocation="John";
        objCA.Select("selectDoc", "id", SelectedDoctor);
        objCA.Select("selectLoc", "id", SelectedLocation);       
      
        objTask.ClickTimeSlot(objCA, "01", "15", "pm");           
       
        String patFName="Jane";
        String patLName="Test";
        objTask.ScheduleAppt(objCA, patLName, patFName);
       
        String dateString = objTask.CurrentDateInFormat("MM-dd-yyyy");
       
        objTask.GoToHomePg(objCA);
        objCA.SwitchToFrame("mainFrame");
        String locName=objCA.GetAttributeValue("//table[@id='ApptTab']/tbody/tr/td","xpath","text");
       
        objTask.Navigate_Menu_Submenu(objCA, "appmnt", "Schedule");   
       
        objCA.SwitchToWindow("WindowTitle1");
        objCA.SwitchToFrame("SchedulerFrame");
        int countPatients=objCA.CountOfElements("//div[@class='apptdivbooked']");
       
        String strText = dateString+" "+SelectedDoctor+" "+locName+" Count #"+countPatients;
        System.out.println("strText: "+strText);   
       
        objCA.SwitchToWindow("WindowTitle1");
        objCA.SwitchToFrame("ApptBottom");
        objCA.Click("//input[@value='count...' and @name='Legend']", "xpath");       
        String alertText=objCA.SwitchToAlert();
       
        if(!strText.equals(alertText)){
            System.out.println("The count alert shows invalid information.");
        }else{
            System.out.println("The count alert shows valid information.");
        }
       
        objTask.MassSchedule(objCA, patLName, patFName);
       
        objCA.SwitchToWindow("WindowTitle1");
        objCA.SwitchToFrame("CalendarFrame");
        String tomorrowsDate = objTask.DateAdd(dateString,1);
       
        @SuppressWarnings("deprecation")
        Date tomDt = new Date(tomorrowsDate);
        int currentDay=tomDt.getDay();
      
        objCA.Click("//input[@class='date' and @value='"+currentDay+"']", "xpath");
        objCA.SwitchToWindow("WindowTitle1");
        objCA.SwitchToFrame("SchedulerFrame");       
     
        objTask.LogOut(objCA);
       
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

No comments:

Post a Comment