Example usage for org.openqa.selenium.support.ui ExpectedConditions elementToBeClickable

List of usage examples for org.openqa.selenium.support.ui ExpectedConditions elementToBeClickable

Introduction

In this page you can find the example usage for org.openqa.selenium.support.ui ExpectedConditions elementToBeClickable.

Prototype

public static ExpectedCondition<WebElement> elementToBeClickable(final WebElement element) 

Source Link

Document

An expectation for checking an element is visible and enabled such that you can click it.

Usage

From source file:com.partnet.automation.HtmlView.java

License:Apache License

/**
 * Waits a specified amount of time for an element to become clickable.
 * //from w  w w. j  a v  a  2s .  c o m
 * @param elm element to wait for
 * @param maxWaitSeconds seconds to wait
 * @throws TimeoutException if timeout has been reached
 */
protected void waitForElementToBeClickable(WebElement elm, int maxWaitSeconds) {
    WebDriverWait wait = new WebDriverWait(webDriver, maxWaitSeconds);
    wait.until(ExpectedConditions.elementToBeClickable(elm));
}

From source file:com.pentaho.ctools.cdf.MetaLayerHomeDashboard.java

License:Apache License

/**
 * ############################### Test Case 1 ###############################
 *
 * Test Case Name:// ww w.j  a  v  a  2s .  c o  m
 *    MetaLayer Home Dashboard - clicking details
 * Description:
 *    We pretend to validate when user click on 'Details...' a pop-up message
 *    is displayed.
 * Steps:
 *    1. Open the MetaLayer Home Dashboard.
 *    2. Click in 'Details...'.
 *    3. Check if we have width = 500 and height = 600
 */
@Test
public void tc1_LinkDetails_PopupJPivot() {
    this.log.info("tc1_LinkDetails_PopupJPivot");
    /*
     * ## Step 1
     */
    driver.get(baseUrl
            + "api/repos/%3Apublic%3Aplugin-samples%3Apentaho-cdf%3A20-samples%3Ahome_dashboard_2%3Ahome_dashboard_metalayer.xcdf/generatedContent");

    //NOTE - we have to wait for loading disappear
    this.elemHelper.WaitForElementInvisibility(driver, By.cssSelector("div.blockUI.blockOverlay"));

    //Wait for title become visible and with value 'Community Dashboard Framework'
    String titlePage = this.elemHelper.WaitForTitle(driver, "Community Dashboard Framework");
    //Wait for visibility of 'Top Ten Customers'
    String expectedSampleTitle = "Top Ten Customers";
    String actualSampleTitle = this.elemHelper.WaitForTextPresence(driver, By.xpath("//div[@id='titleObject']"),
            expectedSampleTitle);
    // Validate the sample that we are testing is the one
    assertEquals(titlePage, "Community Dashboard Framework");
    assertEquals(actualSampleTitle, expectedSampleTitle);

    /*
     * ## Step 2
     */
    //Wait for visibility of 'topTenCustomersDetailsObject' the text 'Details'
    WebElement linkDetails = this.elemHelper.FindElement(driver, By.linkText("Details..."));
    assertEquals("Details...", linkDetails.getText());
    //click on the 'Details...'
    linkDetails.click();

    /*
     * ## Step 3
     */
    //Wait for the frame
    this.elemHelper.WaitForElementPresenceAndVisible(driver, By.id("fancybox-content"));
    this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath("//iframe"));
    WebElement frame = this.elemHelper.FindElement(driver, By.xpath("//iframe"));
    String valueFrameAttrSrc = frame.getAttribute("src");

    ///pentaho/plugin/jpivot/Pivot?solution=system&path=%2Fpublic%2Fplugin-samples%2Fpentaho-cdf%2Factions&action=jpivot.xaction&width=500&height=600
    //Check if we have the sizes 500 and 600
    assertTrue(StringUtils.containsIgnoreCase(valueFrameAttrSrc, "&width=500&height=600"));

    //NOTE - we have to wait for loading disappear
    this.elemHelper.WaitForElementInvisibility(driver, By.cssSelector("div.blockUI.blockOverlay"));

    //Wait for the element be visible.
    WebDriver driverFrame = driver.switchTo().frame(frame);
    assertNotNull(this.elemHelper.FindElement(driverFrame, By.xpath("//div[@id='internal_content']")));
    assertEquals("Measures", this.elemHelper.WaitForElementPresentGetText(driverFrame,
            By.xpath("//div[@id='internal_content']/table/tbody/tr[2]/td[2]/p/table/tbody/tr/th[2]")));
    assertEquals("Australian Collectors, Co.", this.elemHelper.WaitForElementPresentGetText(driverFrame, By
            .xpath("//div[@id='internal_content']/table[1]/tbody/tr[2]/td[2]/p[1]/table/tbody/tr[5]/th/div")));
    assertEquals("180,125", this.elemHelper.WaitForElementPresentGetText(driverFrame,
            By.xpath("//div[@id='internal_content']/table[1]/tbody/tr[2]/td[2]/p[1]/table/tbody/tr[7]/td")));

    //Close pop-up
    driver.switchTo().defaultContent();
    wait.until(ExpectedConditions.elementToBeClickable(By.id("fancybox-close")));
    String background = this.elemHelper.FindElement(driver, By.cssSelector("#fancybox-close"))
            .getCssValue("background-image");
    String background1 = background.substring(background.indexOf(34) + 1, background.lastIndexOf(34));
    assertEquals("http://localhost:8080/pentaho/api/repos/pentaho-cdf/js-legacy/lib/fancybox/fancybox.png",
            background1);
    this.elemHelper.FindElement(driver, By.id("fancybox-close")).click();
    this.elemHelper.WaitForElementInvisibility(driver, By.id("fancybox-content"));
    assertEquals("200", Integer.toString(HttpUtils.GetResponseCode(background1, "admin", "password")));
}

From source file:com.pentaho.ctools.cdf.require.MetaLayerHomeDashboard.java

License:Apache License

/**
 * ############################### Test Case 1 ###############################
 *
 * Test Case Name:// w  w  w  .j  av a2s .c om
 *    MetaLayer Home Dashboard - clicking details
 * Description:
 *    We pretend to validate when user click on 'Details...' a pop-up message
 *    is displayed.
 * Steps:
 *    1. Open the MetaLayer Home Dashboard.
 *    2. Click in 'Details...'.
 *    3. Check if we have width = 500 and height = 600
 */
@Test
public void tc1_LinkDetails_PopupJPivot() {
    this.log.info("tc1_LinkDetails_PopupJPivot");

    /*
     * ## Step 1
     */
    driver.get(baseUrl
            + "api/repos/%3Apublic%3Aplugin-samples%3Apentaho-cdf%3Apentaho-cdf-require%3A20-samples%3Ahome_dashboard_2%3Ahome_dashboard_metalayer.xcdf/generatedContent");

    //NOTE - we have to wait for loading disappear
    this.elemHelper.WaitForElementInvisibility(driver, By.cssSelector("div.blockUI.blockOverlay"));

    //Wait for title become visible and with value 'Community Dashboard Framework'
    wait.until(ExpectedConditions.titleContains("Community Dashboard Framework"));
    //Wait for visibility of 'Top Ten Customers'
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@id='titleObject']")));
    // Validate the sample that we are testing is the one
    assertEquals("Community Dashboard Framework", driver.getTitle());
    assertEquals("Top Ten Customers",
            this.elemHelper.WaitForElementPresentGetText(driver, By.xpath("//div[@id='titleObject']")));

    /*
     * ## Step 2
     */
    //Wait for visibility of 'topTenCustomersDetailsObject' the text 'Details'
    WebElement linkDetails = this.elemHelper.FindElement(driver, By.linkText("Details..."));
    assertEquals("Details...", linkDetails.getText());
    //click on the 'Details...'
    linkDetails.click();

    /*
     * ## Step 3
     */
    //Wait for the frame
    this.elemHelper.WaitForElementPresenceAndVisible(driver, By.id("fancybox-content"));
    this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath("//iframe"));
    WebElement frame = this.elemHelper.FindElement(driver, By.xpath("//iframe"));
    String valueFrameAttrSrc = frame.getAttribute("src");

    //Check if we have the sizes 500 and 600
    assertTrue(StringUtils.containsIgnoreCase(valueFrameAttrSrc, "&width=500&height=600"));

    //NOTE - we have to wait for loading disappear
    this.elemHelper.WaitForElementInvisibility(driver, By.cssSelector("div.blockUI.blockOverlay"));

    //Wait for the element be visible.
    WebDriver driverFrame = driver.switchTo().frame(frame);
    assertNotNull(this.elemHelper.FindElement(driverFrame, By.xpath("//div[@id='internal_content']")));
    assertEquals("Measures", this.elemHelper.WaitForElementPresentGetText(driverFrame,
            By.xpath("//div[@id='internal_content']/table/tbody/tr[2]/td[2]/p/table/tbody/tr/th[2]")));
    assertEquals("Australian Collectors, Co.", this.elemHelper.WaitForElementPresentGetText(driverFrame, By
            .xpath("//div[@id='internal_content']/table[1]/tbody/tr[2]/td[2]/p[1]/table/tbody/tr[5]/th/div")));
    assertEquals("180,125", this.elemHelper.WaitForElementPresentGetText(driverFrame,
            By.xpath("//div[@id='internal_content']/table[1]/tbody/tr[2]/td[2]/p[1]/table/tbody/tr[7]/td")));

    //Close pop-up
    driver.switchTo().defaultContent();
    wait.until(ExpectedConditions.elementToBeClickable(By.id("fancybox-close")));
    String background = this.elemHelper.FindElement(driver, By.cssSelector("#fancybox-close"))
            .getCssValue("background-image");
    String background1 = background.substring(background.indexOf(34) + 1, background.lastIndexOf(34));
    assertEquals(baseUrl + "plugin/pentaho-cdf/api/resources/js/compressed/lib/fancybox/fancybox.png",
            background1);
    this.elemHelper.ClickJS(driver, By.id("fancybox-close"));
    this.elemHelper.WaitForElementInvisibility(driver, By.id("fancybox-content"));
    assertEquals("200", Integer.toString(HttpUtils.GetResponseCode(background1, "admin", "password")));
}

From source file:com.pentaho.ctools.cdf.require.SchedulePrptComponent.java

License:Apache License

/**
 * ############################### Test Case 2 ###############################
 *
 * Test Case Name:/*from  w  ww  .  ja v a2  s  . co m*/
 *    Create a Schedule
 * Description:
 *    It is supposed to create a schedule and validate it was created with
 *    specify data and date.
 * Steps:
 *    1. Click to create a schedule prpt.
 *    2. Fill the form and submit
 *    3. Check for alert.
 *    4. On Schedule Manager, it is set the schedule.
 * @throws InterruptedException
 */
@Test
public void tc3_SchedulePrpt_ScheduleCreatedSuccessful() {
    this.log.info("tc3_SchedulePrpt_ScheduleCreatedSuccessful");
    this.bRemoveSchedule = true;
    String schLocation = "/public";

    //Initialize some data
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    SimpleDateFormat sdfDay = new SimpleDateFormat("d");
    Date dNow = new Date();
    Calendar c = Calendar.getInstance();
    c.setTime(dNow);
    c.add(Calendar.DATE, 1);
    Date dTomorrow = c.getTime();
    c.add(Calendar.DATE, 40); //30th days from today
    Date d40days = c.getTime();

    /*
     * ## Step 1
     */
    this.elemHelper.FindElement(driver, By.xpath("//div[@id='sampleObject']/button")).click();

    /*
     * ## Step 2
     */
    wait.until(ExpectedConditions.presenceOfElementLocated(By.id("jqistate_basicState")));
    //Set schedule name
    this.elemHelper.FindElement(driver, By.id("nameIn")).clear();
    this.elemHelper.FindElement(driver, By.id("nameIn")).sendKeys(this.schNameTc3);
    //Set schedule location
    this.elemHelper.FindElement(driver, By.id("locationIn")).clear();
    this.elemHelper.FindElement(driver, By.id("locationIn")).sendKeys(schLocation);
    //Select Monthly
    Select slRecurrence = new Select(this.elemHelper.FindElement(driver, By.id("recurrId")));
    slRecurrence.selectByValue("monthly");
    //Select Hour
    Select slHours = new Select(this.elemHelper.FindElement(driver, By.id("hours")));
    slHours.selectByValue("9");
    //Select Minutes
    Select slMinutes = new Select(this.elemHelper.FindElement(driver, By.id("minutes")));
    slMinutes.selectByValue("17");
    //Select AM/FM
    Select slAMFM = new Select(this.elemHelper.FindElement(driver, By.id("amPm")));
    slAMFM.selectByValue("pm");
    //Select Option 'The x y of every month
    this.elemHelper.Click(driver, By.xpath("//div[@id='patternMonth']/input[2]"));
    //Select Month
    Select slOccDay = new Select(this.elemHelper.FindElement(driver, By.id("monthOpt1Select")));
    slOccDay.selectByValue("1");
    //Select Wednesday
    Select slWeekday = new Select(this.elemHelper.FindElement(driver, By.id("monthOpt2Select")));
    slWeekday.selectByValue("3");
    //Select Range Of Recurrence
    //Start - tomorrow
    this.elemHelper.FindElement(driver, By.id("rangeStartIn")).clear();
    this.elemHelper.FindElement(driver, By.id("rangeStartIn")).sendKeys(sdf.format(dTomorrow));
    wait.until(ExpectedConditions
            .visibilityOfElementLocated(By.xpath("//table[@class='ui-datepicker-calendar']")));
    WebElement dateCalendar = this.elemHelper.FindElement(driver,
            By.xpath("//table[@class='ui-datepicker-calendar']"));
    List<WebElement> columns = dateCalendar.findElements(By.tagName("td"));
    String tomorrowDay = sdfDay.format(dTomorrow);
    for (WebElement cell : columns) {
        String strCell = cell.getText();
        if (strCell.equals(tomorrowDay)) {
            cell.findElement(By.linkText(tomorrowDay)).click();
            break;
        }
    }
    //End
    //Select End Date
    wait.until(ExpectedConditions.elementToBeClickable(By.id("endByRadio")));
    this.elemHelper.FindElement(driver, By.id("endByRadio")).click();
    this.elemHelper.FindElement(driver, By.id("endByIn")).sendKeys(sdf.format(d40days));
    wait.until(ExpectedConditions
            .visibilityOfElementLocated(By.xpath("//table[@class='ui-datepicker-calendar']")));
    WebElement dateCalendar2 = this.elemHelper.FindElement(driver,
            By.xpath("//table[@class='ui-datepicker-calendar']"));
    List<WebElement> columns2 = dateCalendar2.findElements(By.tagName("td"));
    String day = sdfDay.format(d40days);
    for (WebElement cell2 : columns2) {
        String strCell2 = cell2.getText();
        if (strCell2.equals(day)) {
            cell2.findElement(By.linkText(day)).click();
            break;
        }
    }

    //Submit Form
    wait.until(ExpectedConditions.elementToBeClickable(By.id("jqi_basicState_buttonOk")));
    this.elemHelper.FindElement(driver, By.id("jqi_basicState_buttonOk")).click();
    //Wait for the new window.
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("jqistate_mailState")));
    wait.until(ExpectedConditions.elementToBeClickable(By.id("jqi_mailState_buttonOk")));
    this.elemHelper.FindElement(driver, By.id("jqi_mailState_buttonOk")).click();

    // ## Step 3
    wait.until(ExpectedConditions.alertIsPresent());
    Alert alert = driver.switchTo().alert();
    String confirmationMsg = alert.getText();
    alert.accept();
    assertEquals(confirmationMsg, "Successfully scheduled.");

    /*
     * ## Step 4
     */
    //-->Need to check if the schedule was created
    //Go to home page
    driver.get(PageUrl.PUC);

    // NOTE - we have to wait for loading disappear
    this.elemHelper.WaitForElementInvisibility(driver,
            By.xpath("//div[@class='busy-indicator-container waitPopup']"));

    //Click in Schedule
    wait.until(ExpectedConditions.titleContains("Pentaho User Console"));
    wait.until(ExpectedConditions
            .visibilityOfElementLocated(By.xpath("//div[@id='pucUserDropDown']/table/tbody/tr/td/div")));
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//iframe[@id='home.perspective']")));
    wait.until(ExpectedConditions
            .elementToBeClickable(By.xpath("//div[@id='mantle-perspective-switcher']/table/tbody/tr/td[2]")));
    this.elemHelper
            .FindElement(driver, By.xpath("//div[@id='mantle-perspective-switcher']/table/tbody/tr/td[2]"))
            .click();
    WebElement listMenyTr = this.elemHelper.FindElement(driver,
            By.xpath("//div[@id='customDropdownPopupMajor']/div/div/table/tbody"));
    List<WebElement> listMenuElementsTrs = listMenyTr.findElements(By.xpath("//td[@class='gwt-MenuItem']"));
    for (int i = 0; i < listMenuElementsTrs.size(); i++) {
        WebElement element = listMenuElementsTrs.get(i);
        if (element.getText().equals("Schedules")) {
            element.click();
            break;
        }
    }
    wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("div.workspaceHeading")));
    // Now we are in Schedule page
    List<WebElement> listScheduleTrs = this.elemHelper
            .FindElement(driver, By.xpath("//table[@id='schedule-table']/tbody"))
            .findElements(By.tagName("tr"));
    String scheduleName = "";
    String scheduleRepeats = "";
    String scheduleSourceFile = "";
    String scheduleOuputLocation = "";
    String scheduleLastRun = "";
    String scheduleNextRun = "";
    String scheduleCreatedBy = "";
    String scheduleStatus = "";
    for (int j = 1; j <= listScheduleTrs.size(); j++) {
        WebElement elementFirstDiv = this.elemHelper.FindElement(driver,
                By.xpath("//table[@id='schedule-table']/tbody/tr[" + j + "]/td/div"));
        scheduleName = elementFirstDiv.getText();
        if (scheduleName.equals(this.schNameTc3)) {

            scheduleRepeats = this.elemHelper.WaitForElementPresentGetText(driver,
                    By.xpath("//table[@id='schedule-table']/tbody/tr[" + j + "]/td[2]/div"));
            scheduleSourceFile = this.elemHelper.WaitForElementPresentGetText(driver,
                    By.xpath("//table[@id='schedule-table']/tbody/tr[" + j + "]/td[3]/div"));
            scheduleOuputLocation = this.elemHelper.WaitForElementPresentGetText(driver,
                    By.xpath("//table[@id='schedule-table']/tbody/tr[" + j + "]/td[4]/div"));
            scheduleLastRun = this.elemHelper.WaitForElementPresentGetText(driver,
                    By.xpath("//table[@id='schedule-table']/tbody/tr[" + j + "]/td[5]/div"));
            scheduleNextRun = this.elemHelper.WaitForElementPresentGetText(driver,
                    By.xpath("//table[@id='schedule-table']/tbody/tr[" + j + "]/td[6]/div"));
            scheduleCreatedBy = this.elemHelper.WaitForElementPresentGetText(driver,
                    By.xpath("//table[@id='schedule-table']/tbody/tr[" + j + "]/td[7]/div"));
            scheduleStatus = this.elemHelper.WaitForElementPresentGetText(driver,
                    By.xpath("//table[@id='schedule-table']/tbody/tr[" + j + "]/td[8]/div"));
            break;
        }
    }

    //Getting the week day of next run
    String dayOfWeek = "";
    if (!scheduleNextRun.isEmpty()) {
        try {
            Date dateNextRun = new SimpleDateFormat("yyyy MMM dd HH:mm:ss", Locale.US).parse(scheduleNextRun);
            dayOfWeek = new SimpleDateFormat("EE", Locale.US).format(dateNextRun);
        } catch (ParseException pe) {
            this.log.error(pe.getMessage());
        }
    }

    assertEquals(this.schNameTc3, scheduleName);
    assertEquals("The second Wednesday of every month at 21:17:00", scheduleRepeats);
    assertEquals("/public/Steel Wheels/Widget Library/Report Snippets/InventorybyLine", scheduleSourceFile);
    assertEquals(schLocation, scheduleOuputLocation);
    assertEquals("-", scheduleLastRun);
    assertEquals("Wed", dayOfWeek);
    assertEquals("admin", scheduleCreatedBy);
    assertEquals("Normal", scheduleStatus);
}

From source file:com.pentaho.ctools.cdf.require.SchedulePrptComponent.java

License:Apache License

/**
 * This method will remove all created schedules on the tests.
 * Note - for a new schedule update code.
 */// w w w.j  a  v  a  2s .  c  o  m
private void removeAllCreatedSchedules() {
    this.log.info("removeAllCreatedSchedules");
    //Go to home page
    driver.get(PageUrl.PUC);
    // NOTE - we have to wait for loading disappear
    this.elemHelper.WaitForElementInvisibility(driver,
            By.xpath("//div[@class='busy-indicator-container waitPopup']"));

    //Click in Schedule
    wait.until(ExpectedConditions.titleContains("Pentaho User Console"));
    wait.until(ExpectedConditions
            .visibilityOfElementLocated(By.xpath("//div[@id='pucUserDropDown']/table/tbody/tr/td/div")));
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//iframe[@id='home.perspective']")));
    wait.until(ExpectedConditions
            .elementToBeClickable(By.xpath("//div[@id='mantle-perspective-switcher']/table/tbody/tr/td[2]")));
    this.elemHelper
            .FindElement(driver, By.xpath("//div[@id='mantle-perspective-switcher']/table/tbody/tr/td[2]"))
            .click();
    WebElement listMenyTr = this.elemHelper.FindElement(driver,
            By.xpath("//div[@id='customDropdownPopupMajor']/div/div/table/tbody"));
    List<WebElement> listMenuElementsTrs = listMenyTr.findElements(By.xpath("//td[@class='gwt-MenuItem']"));
    for (int i = 0; i < listMenuElementsTrs.size(); i++) {
        WebElement element = listMenuElementsTrs.get(i);
        if (element.getText().equals("Schedules")) {
            element.click();
            break;
        }
    }

    wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("div.workspaceHeading")));

    // Now we are in Schedule page
    Boolean someThingToDelete = true;
    int listElements = 0;
    int listElementsPrevious = -1;
    while (someThingToDelete) {
        someThingToDelete = false;
        List<WebElement> listScheduleTrs = this.elemHelper
                .FindElement(driver, By.xpath("//table[@id='schedule-table']/tbody"))
                .findElements(By.tagName("tr"));
        listElements = listScheduleTrs.size();

        //The new list must be different from previous list
        while (listElements == listElementsPrevious) {
            listScheduleTrs = this.elemHelper
                    .FindElement(driver, By.xpath("//table[@id='schedule-table']/tbody"))
                    .findElements(By.tagName("tr"));
            listElements = listScheduleTrs.size();
        }

        for (int j = 1; j <= listElements; j++) {
            WebElement elementFirstDiv = this.elemHelper.FindElement(driver,
                    By.xpath("//table[@id='schedule-table']/tbody/tr[" + j + "]/td/div"));

            if (elementFirstDiv.getText().equals(this.schNameTc3)) {
                elementFirstDiv.click(); //Select the row

                //Wait for row to be selected
                for (int t = 0; t < 100; t++) {
                    WebElement elementRow = this.elemHelper.FindElement(driver,
                            By.xpath("//table[@id='schedule-table']/tbody/tr[" + j + "]"));

                    if (elementRow.getAttribute("class").contains("cellTableSelectedRow")) {
                        break;
                    }
                }

                //Click to remove the schedule item (the selected row)
                this.elemHelper.Click(driver, By.cssSelector("img.gwt-Image.pentaho-deletebutton"));
                this.elemHelper.WaitForElementPresenceAndVisible(driver,
                        By.xpath("//div[@class='pentaho-dialog']"));
                this.elemHelper.Click(driver, By.id("okButton"));

                this.elemHelper.WaitForElementInvisibility(driver, By.xpath("//div[@class='pentaho-dialog']"));

                someThingToDelete = true; //Continue checking if there is something to delete
                break;
            }
        }
        listElementsPrevious = listElements;
    }
}

From source file:com.pentaho.ctools.cdf.SchedulePrptComponent.java

License:Apache License

/**
 * ############################### Test Case 2 ###############################
 *
 * Test Case Name:// w w w. ja v  a2  s  .  c om
 *    Create a Schedule
 * Description:
 *    It is supposed to create a schedule and validate it was created with
 *    specify data and date.
 * Steps:
 *    1. Click to create a schedule prpt.
 *    2. Fill the form and submit
 *    3. Check for alert.
 *    4. On Schedule Manager, it is set the schedule.
 * @throws InterruptedException
 */
@Test
public void tc3_SchedulePrpt_ScheduleCreatedSuccessful() {
    this.log.info("tc3_SchedulePrpt_ScheduleCreatedSuccessful");
    this.bRemoveSchedule = true;

    String schLocation = "/public";

    //Initialize some data
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    SimpleDateFormat sdfDay = new SimpleDateFormat("d");
    Date dNow = new Date();
    Calendar c = Calendar.getInstance();
    c.setTime(dNow);
    c.add(Calendar.DATE, 1);
    Date dTomorrow = c.getTime();
    c.add(Calendar.DATE, 40); //30th days from today
    Date d40days = c.getTime();

    // ## Step 1
    this.elemHelper.FindElement(driver, By.xpath("//span[@id='sampleObject']/button")).click();

    // ## Step 2
    wait.until(ExpectedConditions.presenceOfElementLocated(By.id("jqistate_basicState")));
    //Set schedule name
    this.elemHelper.FindElement(driver, By.id("nameIn")).clear();
    this.elemHelper.FindElement(driver, By.id("nameIn")).sendKeys(this.schNameTc3);
    //Set schedule location
    this.elemHelper.FindElement(driver, By.id("locationIn")).clear();
    this.elemHelper.FindElement(driver, By.id("locationIn")).sendKeys(schLocation);
    //Select Monthly
    Select slRecurrence = new Select(this.elemHelper.FindElement(driver, By.id("recurrId")));
    slRecurrence.selectByValue("monthly");
    //Select Hour
    Select slHours = new Select(this.elemHelper.FindElement(driver, By.id("hours")));
    slHours.selectByValue("9");
    //Select Minutes
    Select slMinutes = new Select(this.elemHelper.FindElement(driver, By.id("minutes")));
    slMinutes.selectByValue("17");
    //Select AM/FM
    Select slAMFM = new Select(this.elemHelper.FindElement(driver, By.id("amPm")));
    slAMFM.selectByValue("pm");
    //Select Option 'The x y of every month
    this.elemHelper.FindElement(driver, By.xpath("//div[@id='patternMonth']/input[2]")).click();
    //Select Month
    Select slOccDay = new Select(this.elemHelper.FindElement(driver, By.id("monthOpt1Select")));
    slOccDay.selectByValue("1");
    //Select Wednesday
    Select slWeekday = new Select(this.elemHelper.FindElement(driver, By.id("monthOpt2Select")));
    slWeekday.selectByValue("3");
    //Select Range Of Recurrence
    //Start - tomorrow
    this.elemHelper.FindElement(driver, By.id("rangeStartIn")).clear();
    this.elemHelper.FindElement(driver, By.id("rangeStartIn")).sendKeys(sdf.format(dTomorrow));
    this.elemHelper.Click(driver, By.id("rangeStartIn"));
    wait.until(ExpectedConditions
            .visibilityOfElementLocated(By.xpath("//table[@class='ui-datepicker-calendar']")));
    WebElement dateCalendar = this.elemHelper.FindElement(driver,
            By.xpath("//table[@class='ui-datepicker-calendar']"));
    List<WebElement> columns = dateCalendar.findElements(By.tagName("td"));
    String tomorrowDay = sdfDay.format(dTomorrow);
    for (WebElement cell : columns) {
        String strCell = cell.getText();
        if (strCell.equals(tomorrowDay)) {
            cell.findElement(By.linkText(tomorrowDay)).click();
            break;
        }
    }
    //End
    //Select End Date
    wait.until(ExpectedConditions.elementToBeClickable(By.id("endByRadio")));
    this.elemHelper.FindElement(driver, By.id("endByRadio")).click();
    this.elemHelper.FindElement(driver, By.id("endByIn")).sendKeys(sdf.format(d40days));
    this.elemHelper.FindElement(driver, By.id("endByIn")).click();
    wait.until(ExpectedConditions
            .visibilityOfElementLocated(By.xpath("//table[@class='ui-datepicker-calendar']")));
    WebElement dateCalendar2 = this.elemHelper.FindElement(driver,
            By.xpath("//table[@class='ui-datepicker-calendar']"));
    List<WebElement> columns2 = dateCalendar2.findElements(By.tagName("td"));
    String day = sdfDay.format(d40days);
    for (WebElement cell2 : columns2) {
        String strCell2 = cell2.getText();
        if (strCell2.equals(day)) {
            cell2.findElement(By.linkText(day)).click();
            break;
        }
    }

    //Submit Form
    wait.until(ExpectedConditions.elementToBeClickable(By.id("jqi_basicState_buttonOk")));
    this.elemHelper.FindElement(driver, By.id("jqi_basicState_buttonOk")).click();
    //Wait for the new window.
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("jqistate_mailState")));
    wait.until(ExpectedConditions.elementToBeClickable(By.id("jqi_mailState_buttonOk")));
    this.elemHelper.FindElement(driver, By.id("jqi_mailState_buttonOk")).click();

    // ## Step 3
    wait.until(ExpectedConditions.alertIsPresent());
    Alert alert = driver.switchTo().alert();
    String confirmationMsg = alert.getText();
    alert.accept();
    assertEquals(confirmationMsg, "Successfully scheduled.");

    // ## Step 4
    //-->Need to check if the schedule was created
    //Go to home page
    driver.get(PageUrl.PUC);

    // NOTE - we have to wait for loading disappear
    this.elemHelper.WaitForElementInvisibility(driver,
            By.xpath("//div[@class='busy-indicator-container waitPopup']"));

    //Click in Schedule
    wait.until(ExpectedConditions.titleContains("Pentaho User Console"));
    wait.until(ExpectedConditions
            .visibilityOfElementLocated(By.xpath("//div[@id='pucUserDropDown']/table/tbody/tr/td/div")));
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//iframe[@id='home.perspective']")));
    wait.until(ExpectedConditions
            .elementToBeClickable(By.xpath("//div[@id='mantle-perspective-switcher']/table/tbody/tr/td[2]")));
    this.elemHelper
            .FindElement(driver, By.xpath("//div[@id='mantle-perspective-switcher']/table/tbody/tr/td[2]"))
            .click();
    WebElement listMenyTr = this.elemHelper.FindElement(driver,
            By.xpath("//div[@id='customDropdownPopupMajor']/div/div/table/tbody"));
    List<WebElement> listMenuElementsTrs = listMenyTr.findElements(By.xpath("//td[@class='gwt-MenuItem']"));
    for (int i = 0; i < listMenuElementsTrs.size(); i++) {
        WebElement element = listMenuElementsTrs.get(i);
        if (element.getText().equals("Schedules")) {
            element.click();
            break;
        }
    }
    wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("div.workspaceHeading")));
    // Now we are in Schedule page
    List<WebElement> listScheduleTrs = this.elemHelper
            .FindElement(driver, By.xpath("//table[@id='schedule-table']/tbody"))
            .findElements(By.tagName("tr"));
    String scheduleName = "";
    String scheduleRepeats = "";
    String scheduleSourceFile = "";
    String scheduleOuputLocation = "";
    String scheduleLastRun = "";
    String scheduleNextRun = "";
    String scheduleCreatedBy = "";
    String scheduleStatus = "";
    for (int j = 1; j <= listScheduleTrs.size(); j++) {
        WebElement elementFirstDiv = this.elemHelper.FindElement(driver,
                By.xpath("//table[@id='schedule-table']/tbody/tr[" + j + "]/td/div"));
        scheduleName = elementFirstDiv.getText();
        if (scheduleName.equals(this.schNameTc3)) {

            scheduleRepeats = this.elemHelper.WaitForElementPresentGetText(driver,
                    By.xpath("//table[@id='schedule-table']/tbody/tr[" + j + "]/td[2]/div"));
            scheduleSourceFile = this.elemHelper.WaitForElementPresentGetText(driver,
                    By.xpath("//table[@id='schedule-table']/tbody/tr[" + j + "]/td[3]/div"));
            scheduleOuputLocation = this.elemHelper.WaitForElementPresentGetText(driver,
                    By.xpath("//table[@id='schedule-table']/tbody/tr[" + j + "]/td[4]/div"));
            scheduleLastRun = this.elemHelper.WaitForElementPresentGetText(driver,
                    By.xpath("//table[@id='schedule-table']/tbody/tr[" + j + "]/td[5]/div"));
            scheduleNextRun = this.elemHelper.WaitForElementPresentGetText(driver,
                    By.xpath("//table[@id='schedule-table']/tbody/tr[" + j + "]/td[6]/div"));
            scheduleCreatedBy = this.elemHelper.WaitForElementPresentGetText(driver,
                    By.xpath("//table[@id='schedule-table']/tbody/tr[" + j + "]/td[7]/div"));
            scheduleStatus = this.elemHelper.WaitForElementPresentGetText(driver,
                    By.xpath("//table[@id='schedule-table']/tbody/tr[" + j + "]/td[8]/div"));
            break;
        }
    }

    //Getting the week day of next run
    String dayOfWeek = "";
    if (!scheduleNextRun.isEmpty()) {
        try {
            Date dateNextRun = new SimpleDateFormat("yyyy MMM dd HH:mm:ss", Locale.US).parse(scheduleNextRun);
            dayOfWeek = new SimpleDateFormat("EE", Locale.US).format(dateNextRun);
        } catch (ParseException pe) {
            this.log.error(pe.getMessage());
        }
    }

    assertEquals(this.schNameTc3, scheduleName);
    assertEquals("The second Wednesday of every month at 21:17:00", scheduleRepeats);
    assertEquals("/public/Steel Wheels/Widget Library/Report Snippets/InventorybyLine", scheduleSourceFile);
    assertEquals(schLocation, scheduleOuputLocation);
    assertEquals("-", scheduleLastRun);
    assertEquals("Wed", dayOfWeek);
    assertEquals("admin", scheduleCreatedBy);
    assertEquals("Normal", scheduleStatus);
}

From source file:com.pentaho.ctools.cdf.SchedulePrptComponent.java

License:Apache License

/**
 * This method will remove all created schedules on the tests.
 * Note - for a new schedule update code.
 *///  w w  w. j a  v a 2s.co m
private void removeAllCreatedSchedules() {
    this.log.info("removeAllCreatedSchedules");

    //Go to home page
    driver.get(PageUrl.PUC);
    // NOTE - we have to wait for loading disappear
    this.elemHelper.WaitForElementInvisibility(driver,
            By.xpath("//div[@class='busy-indicator-container waitPopup']"));

    //Click in Schedule
    wait.until(ExpectedConditions.titleContains("Pentaho User Console"));
    wait.until(ExpectedConditions
            .visibilityOfElementLocated(By.xpath("//div[@id='pucUserDropDown']/table/tbody/tr/td/div")));
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//iframe[@id='home.perspective']")));
    wait.until(ExpectedConditions
            .elementToBeClickable(By.xpath("//div[@id='mantle-perspective-switcher']/table/tbody/tr/td[2]")));
    this.elemHelper
            .FindElement(driver, By.xpath("//div[@id='mantle-perspective-switcher']/table/tbody/tr/td[2]"))
            .click();
    WebElement listMenyTr = this.elemHelper.FindElement(driver,
            By.xpath("//div[@id='customDropdownPopupMajor']/div/div/table/tbody"));
    List<WebElement> listMenuElementsTrs = listMenyTr.findElements(By.xpath("//td[@class='gwt-MenuItem']"));
    for (int i = 0; i < listMenuElementsTrs.size(); i++) {
        WebElement element = listMenuElementsTrs.get(i);
        if (element.getText().equals("Schedules")) {
            element.click();
            break;
        }
    }

    wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("div.workspaceHeading")));

    // Now we are in Schedule page
    Boolean someThingToDelete = true;
    int listElements = 0;
    int listElementsPrevious = -1;
    while (someThingToDelete) {
        someThingToDelete = false;
        List<WebElement> listScheduleTrs = this.elemHelper
                .FindElement(driver, By.xpath("//table[@id='schedule-table']/tbody"))
                .findElements(By.tagName("tr"));
        listElements = listScheduleTrs.size();

        //The new list must be different from previous list
        while (listElements == listElementsPrevious) {
            listScheduleTrs = this.elemHelper
                    .FindElement(driver, By.xpath("//table[@id='schedule-table']/tbody"))
                    .findElements(By.tagName("tr"));
            listElements = listScheduleTrs.size();
        }

        for (int j = 1; j <= listElements; j++) {
            WebElement elementFirstDiv = this.elemHelper.FindElement(driver,
                    By.xpath("//table[@id='schedule-table']/tbody/tr[" + j + "]/td/div"));

            if (elementFirstDiv.getText().equals(this.schNameTc3)) {
                elementFirstDiv.click(); //Select the row

                //Wait for row to be selected
                for (int t = 0; t < 100; t++) {
                    WebElement elementRow = this.elemHelper.FindElement(driver,
                            By.xpath("//table[@id='schedule-table']/tbody/tr[" + j + "]"));

                    if (elementRow.getAttribute("class").contains("cellTableSelectedRow")) {
                        break;
                    }
                }

                //Click to remove the schedule item (the selected row)
                this.elemHelper.Click(driver, By.cssSelector("img.gwt-Image.pentaho-deletebutton"));
                this.elemHelper.WaitForElementPresenceAndVisible(driver,
                        By.xpath("//div[@class='pentaho-dialog']"));
                this.elemHelper.Click(driver, By.id("okButton"));

                this.elemHelper.WaitForElementInvisibility(driver, By.xpath("//div[@class='pentaho-dialog']"));

                someThingToDelete = true; //Continue checking if there is something to delete
                break;
            }
        }
        listElementsPrevious = listElements;
    }
}

From source file:com.qkn.automation.pages.LoginPage.java

public void DoneEndUserLisence() throws Exception {
    WebDriverWait wait = new WebDriverWait(pageDriver, 20);
    wait.until(ExpectedConditions.elementToBeClickable(By.xpath(pageprops.getProperty("DONE_BTN"))));
    pageDriver.findElement(By.xpath(pageprops.getProperty("DONE_BTN"))).click();
    //   Thread.sleep(5000);

}

From source file:com.redskyit.scriptDriver.RunTests.java

License:MIT License

private void runCommand(final StreamTokenizer tokenizer, File file, String source, ExecutionContext script)
        throws Exception {
    // Automatic log dumping
    if (autolog && null != driver) {
        dumpLog();/*w w  w. j av a  2 s . co  m*/
    }

    String cmd = tokenizer.sval;
    System.out.printf((new Date()).getTime() + ": [%s,%d] ", source, tokenizer.lineno());
    System.out.print(tokenizer.sval);

    if (cmd.equals("version")) {
        // HELP: version
        System.out.println();
        System.out.println("ScriptDriver version " + version);
        return;
    }

    if (cmd.equals("browser")) {
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            System.out.print(' ');
            System.out.print(tokenizer.sval);

            if (tokenizer.sval.equals("prefs")) {
                // HELP: browser prefs ...
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                    System.out.print(' ');
                    System.out.print(tokenizer.sval);
                    String pref = tokenizer.sval;
                    tokenizer.nextToken();
                    System.out.print(' ');
                    if (_skip)
                        return;
                    if (null == options)
                        options = new ChromeOptions();
                    if (null == prefs)
                        prefs = new HashMap<String, Object>();
                    switch (tokenizer.ttype) {
                    case StreamTokenizer.TT_WORD:
                    case '"':
                        System.out.println(tokenizer.sval);
                        if (tokenizer.sval.equals("false")) {
                            prefs.put(pref, false);
                        } else if (tokenizer.sval.equals("true")) {
                            prefs.put(pref, true);
                        } else {
                            prefs.put(pref, tokenizer.sval);
                        }
                        return;
                    case StreamTokenizer.TT_NUMBER:
                        System.out.println(tokenizer.nval);
                        prefs.put(pref, tokenizer.nval);
                        return;
                    }
                }
                System.out.println();
                throw new Exception("browser option command argument missing");
            }

            if (tokenizer.sval.equals("option")) {
                // HELP: browser option ...
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') { // expect a quoted string
                    System.out.print(' ');
                    System.out.println(tokenizer.sval);
                    if (_skip)
                        return;
                    if (null == options)
                        options = new ChromeOptions();
                    options.addArguments(tokenizer.sval);
                    return;
                }
                System.out.println();
                throw new Exception("browser option command argument missing");
            }

            // HELP: browser wait <seconds>
            if (tokenizer.sval.equals("wait")) {
                tokenizer.nextToken();
                double nval = script.getExpandedNumber(tokenizer);
                System.out.print(' ');
                System.out.println(nval);
                if (_skip)
                    return;
                driver.manage().timeouts().implicitlyWait((long) (tokenizer.nval * 1000),
                        TimeUnit.MILLISECONDS);
                return;
            }

            if (tokenizer.sval.equals("start")) {
                // HELP: browser start
                System.out.println();
                if (null == driver) {
                    // https://sites.google.com/a/chromium.org/chromedriver/capabilities
                    DesiredCapabilities capabilities = DesiredCapabilities.chrome();
                    LoggingPreferences logs = new LoggingPreferences();
                    logs.enable(LogType.BROWSER, Level.ALL);
                    capabilities.setCapability(CapabilityType.LOGGING_PREFS, logs);
                    if (null == options)
                        options = new ChromeOptions();
                    if (null == prefs)
                        prefs = new HashMap<String, Object>();
                    options.setExperimentalOption("prefs", prefs);
                    options.merge(capabilities);
                    driver = new ChromeDriver(options);
                    driver.setLogLevel(Level.ALL);
                    actions = new Actions(driver); // for advanced actions
                }
                return;
            }

            if (null == driver) {
                System.out.println();
                throw new Exception("browser start must be used before attempt to interract with the browser");
            }

            if (tokenizer.sval.equals("get")) {
                // HELP: browser get "url"
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') { // expect a quoted string
                    System.out.print(' ');
                    System.out.println(tokenizer.sval);
                    if (_skip)
                        return;
                    if (null == driver)
                        driver = new ChromeDriver(options);
                    driver.get(tokenizer.sval);
                    return;
                }
                System.out.println();
                throw new Exception("browser get command argument should be a quoted url");
            }

            if (tokenizer.sval.equals("refresh")) {
                // HELP: browser refresh
                System.out.println();
                driver.navigate().refresh();
                return;
            }

            if (tokenizer.sval.equals("back")) {
                // HELP: browser refresh
                System.out.println();
                driver.navigate().back();
                return;
            }

            if (tokenizer.sval.equals("forward")) {
                // HELP: browser refresh
                System.out.println();
                driver.navigate().forward();
                return;
            }

            if (tokenizer.sval.equals("close")) {
                // HELP: browser close
                System.out.println();
                if (!_skip) {
                    driver.close();
                    autolog = false;
                }
                return;
            }

            if (tokenizer.sval.equals("chrome")) {
                // HELP: browser chrome <width>,<height>
                int w = 0, h = 0;
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                    w = (int) tokenizer.nval;
                    System.out.print(' ');
                    System.out.print(w);
                    tokenizer.nextToken();
                    if (tokenizer.ttype == ',') {
                        tokenizer.nextToken();
                        System.out.print(',');
                        if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                            h = (int) tokenizer.nval;
                            System.out.print(h);
                            System.out.println();
                            if (!_skip) {
                                this.chrome = new Dimension(w, h);
                            }
                            return;
                        }
                    }
                }
                throw new Exception("browser chrome arguments error at line " + tokenizer.lineno());
            }

            if (tokenizer.sval.equals("size")) {
                // HELP: browser size <width>,<height>
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                    final int w = (int) tokenizer.nval;
                    System.out.print(' ');
                    System.out.print(w);
                    tokenizer.nextToken();
                    if (tokenizer.ttype == ',') {
                        tokenizer.nextToken();
                        System.out.print(',');
                        if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                            final int h = (int) tokenizer.nval;
                            System.out.print(h);
                            System.out.println();
                            if (!_skip) {
                                new WaitFor(cmd, tokenizer, false) {
                                    @Override
                                    protected void run() throws RetryException {
                                        Dimension size = new Dimension(chrome.width + w, chrome.height + h);
                                        System.out.println("// chrome " + chrome.toString());
                                        System.out.println("// size with chrome " + size.toString());
                                        try {
                                            driver.manage().window().setSize(size);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                            throw new RetryException("Could not set browser size");
                                        }
                                    }
                                };
                            }
                            return;
                        }
                    }
                }
                throw new Exception("browser size arguments error at line " + tokenizer.lineno());
            }
            if (tokenizer.sval.equals("pos")) {
                // HELP: browser pos <x>,<y>
                int x = 0, y = 0;
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                    x = (int) tokenizer.nval;
                    System.out.print(' ');
                    System.out.print(x);
                    tokenizer.nextToken();
                    if (tokenizer.ttype == ',') {
                        tokenizer.nextToken();
                        System.out.print(',');
                        if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                            y = (int) tokenizer.nval;
                            System.out.print(y);
                            System.out.println();
                            if (!_skip)
                                driver.manage().window().setPosition(new Point(x, y));
                            return;
                        }
                    }
                }
                throw new Exception("browser size arguments error at line " + tokenizer.lineno());
            }
            throw new Exception("browser unknown command argument at line " + tokenizer.lineno());
        }
        throw new Exception("browser missing command argument at line " + tokenizer.lineno());
    }

    if (cmd.equals("alias") || cmd.equals("function")) {
        // HELP: alias <name> { body }
        // HELP: function <name> (param, ...) { body }
        String name = null, args = null;
        List<String> params = null;
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            System.out.print(' ');
            System.out.print(tokenizer.sval);
            name = tokenizer.sval;
            params = getParams(tokenizer);
            args = getBlock(script, tokenizer, ' ', false);
            System.out.println();
            if (_skip)
                return;
            addFunction(name, params, args); // add alias
            return;
        }
        System.out.println();
        throw new Exception("alias name expected");
    }

    if (cmd.equals("while")) {
        // HELP: while { block }
        String block = null;
        block = getBlock(script, tokenizer, ' ', false);
        if (_skip)
            return;
        boolean exitloop = false;
        while (!exitloop) {
            try {
                runString(block, file, "while");
            } catch (Exception e) {
                exitloop = true;
            }
        }
        return;
    }

    if (cmd.equals("include")) {
        // HELP: include <script>
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            if (_skip)
                return;
            System.out.print(' ');
            System.out.println(tokenizer.sval);
            File include = new File(tokenizer.sval.startsWith("/") ? tokenizer.sval
                    : file.getParentFile().getCanonicalPath() + "/" + tokenizer.sval);
            runScript(include.getCanonicalPath());
            return;
        }
        throw new Exception("include argument should be a quoted filename");
    }

    if (cmd.equals("exec")) {
        // HELP: exec <command> { args ... }
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String command = tokenizer.sval;
            System.out.print(' ');
            System.out.print(command);
            List<String> args = getArgs(tokenizer, script);
            File include = new File(command.startsWith("/") ? command
                    : file.getParentFile().getCanonicalPath() + "/" + command);
            command = include.getCanonicalPath();
            System.out.println(command);
            List<String> arguments = new ArrayList<String>();
            arguments.add(command);
            arguments.addAll(args);
            Process process = Runtime.getRuntime().exec(arguments.toArray(new String[arguments.size()]));
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            int exitStatus = process.waitFor();
            if (exitStatus != 0) {
                throw new Exception("exec command returned failure status " + exitStatus);
            }
            return;
        }
        System.out.println();
        throw new Exception("exec argument should be string or a word");
    }

    if (cmd.equals("exec-include")) {
        // HELP: exec-include <command> { args ... }
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String command = tokenizer.sval;
            System.out.print(' ');
            System.out.print(command);
            List<String> args = getArgs(tokenizer, script);
            File include = new File(command.startsWith("/") ? command
                    : file.getParentFile().getCanonicalPath() + "/" + command);
            command = include.getCanonicalPath();
            System.out.println(command);
            List<String> arguments = new ArrayList<String>();
            arguments.add(command);
            arguments.addAll(args);
            Process process = Runtime.getRuntime().exec(arguments.toArray(new String[arguments.size()]));
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String s = "", line = "";
            while ((line = reader.readLine()) != null) {
                s += line + "\n";
            }
            int exitStatus = process.waitFor();
            if (exitStatus != 0) {
                throw new Exception("exec-include command returned failure status " + exitStatus);
            }
            if (s.length() > 0) {
                runString(s, file, tokenizer.sval);
            }
            return;
        }
        System.out.println();
        throw new Exception(cmd + " argument should be string or a word");
    }

    if (cmd.equals("log")) {
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String action = tokenizer.sval;
            System.out.print(' ');
            System.out.print(action);
            if (action.equals("dump")) {
                // HELP: log dump
                System.out.println("");
                if (driver != null)
                    dumpLog();
                return;
            }
            if (action.equals("auto")) {
                // HELP: log auto <on|off>
                // HELP: log auto <true|false>
                tokenizer.nextToken();
                String onoff = tokenizer.sval;
                System.out.print(' ');
                System.out.println(onoff);
                autolog = onoff.equals("on") || onoff.equals("true");
                return;
            }
            System.out.println();
            throw new Exception("invalid log action");
        }
        System.out.println();
        throw new Exception("log argument should be string or a word");
    }

    if (cmd.equals("default")) {
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String action = tokenizer.sval;
            System.out.print(' ');
            System.out.print(action);
            if (action.equals("wait")) {
                // HELP: default wait <seconds>
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                    System.out.print(' ');
                    System.out.println(tokenizer.nval);
                    _defaultWaitFor = (int) (tokenizer.nval * 1000.0);
                }
                return;
            }
            if (action.equals("screenshot")) {
                // HELP: default screenshot <path>
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                    System.out.print(' ');
                    System.out.println(tokenizer.sval);
                    screenShotPath = tokenizer.sval;
                }
                return;
            }
            System.out.println();
            throw new Exception("invalid default property " + tokenizer.sval);
        }
        System.out.println();
        throw new Exception("default argument should be string or a word");
    }

    if (cmd.equals("push")) {
        // HELP: push wait
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String action = tokenizer.sval;
            System.out.print(' ');
            System.out.print(action);
            ArrayList<Object> stack = stacks.get(action);
            if (null == stack) {
                stack = new ArrayList<Object>();
                stacks.put(action, stack);
            }
            if (action.equals("wait")) {
                stack.add(new Long(_waitFor));
                System.out.println();
                return;
            }
        }
        System.out.println();
        throw new Error("Invalid push argument");
    }

    if (cmd.equals("pop")) {
        // HELP: pop wait
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String action = tokenizer.sval;
            System.out.print(' ');
            System.out.print(action);
            ArrayList<Object> stack = stacks.get(action);
            if (null == stack || stack.isEmpty()) {
                throw new Error("pop called without corresponding push");
            }
            if (action.equals("wait")) {
                int index = stack.size() - 1;
                _waitFor = (Long) stack.get(index);
                stack.remove(index);
                System.out.println();
                return;
            }
        }
        System.out.println();
        throw new Error("Invalid push argument");
    }

    if (cmd.equals("echo")) {
        // HELP: echo "string"
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String text = script.getExpandedString(tokenizer);
            System.out.print(' ');
            System.out.println(text);
            if (!_skip)
                System.out.println(text);
            return;
        }
        System.out.println();
        throw new Exception("echo argument should be string or a word");
    }

    if (cmd.equals("sleep")) {
        // HELP: sleep <seconds>
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
            System.out.print(' ');
            System.out.println(tokenizer.nval);
            this.sleep((long) (tokenizer.nval * 1000));
            return;
        }
        System.out.println();
        throw new Exception("sleep command argument should be a number");
    }

    if (cmd.equals("fail")) {
        // HELP: fail "<message>"
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String text = tokenizer.sval;
            System.out.print(' ');
            System.out.println(text);
            if (!_skip) {
                System.out.println("TEST FAIL: " + text);
                throw new Exception(text);
            }
            return;
        }
        System.out.println();
        throw new Exception("echo argument should be string or a word");
    }

    if (cmd.equals("debugger")) {
        // HELP: debugger
        System.out.println();
        this.sleepSeconds(10);
        return;
    }

    if (cmd.equals("if")) {
        // HELP: if <commands> then <commands> [else <commands>] endif
        _if = true;
        System.out.println();
        return;
    }

    if (cmd.equals("then")) {
        _if = false;
        _skip = !_test;
        System.out.println();
        return;
    }

    if (cmd.equals("else")) {
        _if = false;
        _skip = _test;
        System.out.println();
        return;
    }

    if (cmd.equals("endif")) {
        _skip = false;
        System.out.println();
        return;
    }

    if (cmd.equals("not")) {
        // HELP: not <check-command>
        System.out.println();
        _not = true;
        return;
    }

    if (null != driver) {

        // all these command require the browser to have been started

        if (cmd.equals("field") || cmd.equals("id") || cmd.equals("test-id")) {
            // HELP: field "<test-id>"
            // HELP: id "<test-id>"
            // HELP: test-id "<test-id>"
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                if (_skip)
                    return;
                System.out.print(' ');
                this.setContextToField(script, tokenizer);
                return;
            }
            System.out.println();
            throw new Exception(cmd + " command requires a form.field argument");
        }

        if (cmd.equals("select")) {
            // HELP: select "<query-selector>"
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                if (_skip)
                    return;
                System.out.print(' ');
                selectContext(tokenizer, script);
                return;
            }
            System.out.println();
            throw new Exception(cmd + " command requires a css selector argument");
        }

        if (cmd.equals("xpath")) {
            // HELP: xpath "<xpath-expression>"
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                if (_skip)
                    return;
                System.out.print(' ');
                this.xpathContext(script, tokenizer);
                return;
            }
            System.out.println();
            throw new Exception(cmd + " command requires a css selector argument");
        }

        if (cmd.equals("wait")) {
            // HELP: wait <seconds>
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                System.out.print(' ');
                System.out.println(tokenizer.nval);

                // we will repeat then next select type command until it succeeds or we timeout
                _waitFor = (long) ((new Date()).getTime() + (tokenizer.nval * 1000));
                return;
            }

            // HELP: wait <action>
            if (tokenizer.ttype == StreamTokenizer.TT_WORD) {
                String action = tokenizer.sval;
                System.out.println(' ');
                System.out.println(action);
                if (action.equals("clickable")) {
                    long sleep = (_waitFor - (new Date()).getTime()) / 1000;
                    if (sleep > 0) {
                        System.out.println("WebDriverWait for " + sleep + " seconds");
                        WebDriverWait wait = new WebDriverWait(driver, sleep);
                        WebElement element = wait.until(ExpectedConditions.elementToBeClickable(selection));
                        if (element != selection) {
                            throw new Exception("element is not clickable");
                        }
                    } else {
                        System.out.println("WebDriverWait for " + sleep + " seconds (skipped)");
                    }
                    return;
                }
            }
            throw new Exception(cmd + " command requires a seconds argument");
        }

        if (cmd.equals("set") || cmd.equals("send")) {
            // HELP: set "<value>"
            // HELP: send "<value>"
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                if (_skip)
                    return;
                System.out.print(' ');
                System.out.println(script.getExpandedString(tokenizer));
                this.setContextValue(cmd, script, tokenizer, cmd.equals("set"));
                return;
            }
            System.out.println();
            throw new Exception("set command requires a value argument");
        }

        if (cmd.equals("test") || cmd.equals("check")) {
            // HELP: test "<value>"
            // HELP: check "<value>"
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"'
                    || tokenizer.ttype == '\'') {
                if (_skip)
                    return;
                System.out.print(' ');
                System.out.println(script.getExpandedString(tokenizer));
                this.testContextValue(cmd, script, tokenizer, false);
                return;
            }
            System.out.println();
            throw new Exception(cmd + " command requires a value argument");
        }

        if (cmd.equals("checksum")) {
            // HELP: checksum "<checksum>"
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"'
                    || tokenizer.ttype == '\'') {
                if (_skip)
                    return;
                System.out.print(' ');
                System.out.println(script.getExpandedString(tokenizer));
                this.testContextValue(cmd, script, tokenizer, true);
                return;
            }
            System.out.println();
            throw new Exception(cmd + " command requires a value argument");
        }

        if (cmd.equals("click") || cmd.equals("click-now")) {
            // HELP: click
            System.out.println();
            final boolean wait = !cmd.equals("click-now");
            new WaitFor(cmd, tokenizer, true) {
                @Override
                protected void run() throws RetryException {
                    if (!_skip) {
                        if (wait) {
                            long sleep = (_waitFor - (new Date()).getTime()) / 1000;
                            if (sleep > 0) {
                                System.out.println("WebDriverWait for " + sleep + " seconds");
                                WebDriverWait wait = new WebDriverWait(driver, sleep);
                                WebElement element = wait
                                        .until(ExpectedConditions.elementToBeClickable(selection));
                                if (element == selection) {
                                    selection.click();
                                    return;
                                } else {
                                    throw new RetryException("click failed");
                                }
                            }
                        }
                        // click-nowait, no or negative wait period, just click
                        selection.click();
                    }
                }
            };
            return;
        }

        if (cmd.equals("scroll-into-view")) {
            // HELP: scroll-into-view
            System.out.println();
            if (null == selection)
                throw new Exception(cmd + " command requires a field selection at line " + tokenizer.lineno());
            if (!_skip) {
                try {
                    scrollContextIntoView(selection);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                    info(selection, selectionCommand, false);
                    throw e;
                }
            }
            return;
        }

        if (cmd.equals("clear")) {
            // HELP: clear
            System.out.println();
            new WaitFor(cmd, tokenizer, true) {
                @Override
                protected void run() {
                    if (!_skip)
                        selection.clear();
                }
            };
            return;
        }

        if (cmd.equals("call")) {
            // HELP: call <function> { args ... }
            String function = null, args = null;
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') { // expect a quoted string
                function = script.getExpandedString(tokenizer);
                System.out.print(' ');
                System.out.print(function);
                args = getBlock(script, tokenizer, ',', true);
                System.out.println();
                if (_skip)
                    return;
                if (null == args)
                    args = "";
                String js = "var result = window.RegressionTest.test('" + function + "',[" + args + "]);"
                        + "arguments[arguments.length-1](result);";
                System.out.println("> " + js);
                Object result = driver.executeAsyncScript(js);
                if (null != result) {
                    if (result.getClass() == RemoteWebElement.class) {
                        selection = (RemoteWebElement) result;
                        stype = SelectionType.Script;
                        selector = js;
                        System.out.println("new selection " + selection);
                    }
                }
                return;
            }
            System.out.println();
            throw new Exception("missing arguments for call statement at line " + tokenizer.lineno());
        }

        if (cmd.equals("enabled")) {
            // HELP: enabled
            System.out.println();
            new WaitFor(cmd, tokenizer, true) {
                @Override
                protected void run() throws RetryException {
                    if (!_skip) {
                        if (selection.isEnabled() != _not) {
                            _not = false;
                            return;
                        }
                        throw new RetryException("enabled check failed");
                    }
                }
            };
            return;
        }

        if (cmd.equals("selected")) {
            // HELP: selected
            System.out.println();
            new WaitFor(cmd, tokenizer, true) {
                @Override
                protected void run() throws RetryException {
                    if (!_skip) {
                        if (selection.isSelected() != _not) {
                            _not = false;
                            return;
                        }
                        throw new RetryException("selected check failed");
                    }
                }
            };
            return;
        }

        if (cmd.equals("displayed")) {
            // HELP: displayed
            System.out.println();
            new WaitFor(cmd, tokenizer, true) {
                @Override
                protected void run() throws RetryException {
                    if (!_skip) {
                        if (selection.isDisplayed() != _not) {
                            _not = false;
                            return;
                        }
                        throw new RetryException("displayed check failed");
                    }
                }
            };
            return;
        }

        if (cmd.equals("at")) {
            // HELP: at <x|*>,<y>
            int x = 0, y = 0;
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_NUMBER || tokenizer.ttype == '*') {
                x = (int) tokenizer.nval;
                System.out.print(' ');
                if (tokenizer.ttype == '*') {
                    x = -1;
                    System.out.print('*');
                } else {
                    x = (int) tokenizer.nval;
                    System.out.print(x);
                }
                tokenizer.nextToken();
                if (tokenizer.ttype == ',') {
                    tokenizer.nextToken();
                    System.out.print(',');
                    if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                        y = (int) tokenizer.nval;
                        System.out.print(y);
                        System.out.println();
                        final int X = x;
                        final int Y = y;
                        new WaitFor(cmd, tokenizer, true) {
                            @Override
                            protected void run() throws RetryException {
                                if (!_skip) {
                                    Point loc = selection.getLocation();
                                    if (((loc.x == X || X == -1) && loc.y == Y) != _not) {
                                        _not = false;
                                        return;
                                    }
                                    throw new RetryException("location check failed");
                                }
                            }
                        };
                        return;
                    }
                }
            }
            System.out.println();
            throw new Exception("at missing co-ordiantes at line " + tokenizer.lineno());
        }

        if (cmd.equals("size")) {
            // HELP: size <w|*>,<h>
            int mw = 0, w = 0, h = 0;
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_NUMBER || tokenizer.ttype == '*') {
                System.out.print(' ');
                if (tokenizer.ttype == '*') {
                    mw = w = -1;
                    System.out.print('*');
                } else {
                    mw = w = (int) tokenizer.nval;
                    System.out.print(w);
                }
                tokenizer.nextToken();
                if (tokenizer.ttype == ':') {
                    tokenizer.nextToken();
                    w = (int) tokenizer.nval;
                    System.out.print(':');
                    System.out.print(w);
                    tokenizer.nextToken();
                }
                if (tokenizer.ttype == ',') {
                    tokenizer.nextToken();
                    System.out.print(',');
                    if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                        h = (int) tokenizer.nval;
                        System.out.print(h);
                        System.out.println();
                        final int MW = mw;
                        final int W = w;
                        final int H = h;
                        new WaitFor(cmd, tokenizer, true) {
                            @Override
                            protected void run() throws RetryException {
                                if (!_skip) {
                                    Dimension size = selection.getSize();
                                    if (((MW == -1 || (size.width >= MW && size.width <= W))
                                            && size.height == H) != _not) {
                                        _not = false;
                                        return;
                                    }
                                    throw new RetryException("size check failed");
                                }
                            }
                        };
                        return;
                    }
                }
            }
            System.out.println();
            throw new Exception("size missing dimensions at line " + tokenizer.lineno());
        }

        if (cmd.equals("tag")) {
            // HELP: tag <tag-name>
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                System.out.print(' ');
                System.out.print(tokenizer.sval);
                System.out.println();
                new WaitFor(cmd, tokenizer, true) {
                    @Override
                    protected void run() throws RetryException {
                        if (!_skip) {
                            String tag = selection.getTagName();
                            if (tokenizer.sval.equals(tag) != _not) {
                                _not = false;
                                return;
                            }
                            throw new RetryException("tag \"" + tokenizer.sval + "\" check failed, tag is "
                                    + tag + " at line " + tokenizer.lineno());
                        }
                    }
                };
                return;
            }
            System.out.println();
            throw new Exception("tag command has missing tag name at line " + tokenizer.lineno());
        }

        if (cmd.equals("info")) {
            // HELP: info
            System.out.println();
            if (null == selection)
                throw new Exception("info command requires a selection at line " + tokenizer.lineno());
            info(selection, selectionCommand, true);
            return;
        }

        if (cmd.equals("alert")) {
            // HELP: alert accept
            System.out.println();
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                System.out.print(' ');
                System.out.print(tokenizer.sval);
                if (tokenizer.sval.equals("accept")) {
                    System.out.println();
                    if (!_skip)
                        driver.switchTo().alert().accept();
                    return;
                }
            }
            System.out.println();
            throw new Exception("alert syntax error at line " + tokenizer.lineno());
        }

        if (cmd.equals("dump")) {
            // HELP: dump
            System.out.println();
            if (!_skip)
                dump();
            return;
        }

        if (cmd.equals("mouse")) {
            // HELP: mouse { <center|0,0|origin|body|down|up|click|+/-x,+/-y> commands ... }
            parseBlock(script, tokenizer, new BlockHandler() {
                public void parseToken(StreamTokenizer tokenizer, String token) {
                    int l = token.length();
                    if (token.equals("center")) {
                        actions.moveToElement(selection);
                    } else if ((l > 1 && token.substring(1, l - 1).equals("0,0")) || token.equals("origin")) {
                        actions.moveToElement(selection, 0, 0);
                    } else if (token.equals("body")) {
                        actions.moveToElement(driver.findElement(By.tagName("body")), 0, 0);
                    } else if (token.equals("down")) {
                        actions.clickAndHold();
                    } else if (token.equals("up")) {
                        actions.release();
                    } else if (token.equals("click")) {
                        actions.click();
                    } else if (l > 1) {
                        String[] a = token.substring(1, l - 1).split(",");
                        actions.moveByOffset(Integer.valueOf(a[0]), Integer.valueOf(a[1]));
                    } else {
                        // no-op
                    }
                }
            });
            System.out.println();
            actions.release();
            actions.build().perform();
            return;
        }

        if (cmd.equals("screenshot")) {
            // HELP: screenshot "<path>"
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                String path = tokenizer.sval;
                System.out.print(' ');
                System.out.println(path);
                if (!_skip) {
                    WebDriver augmentedDriver = new Augmenter().augment(driver);
                    File screenshot = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE);
                    String outputPath;
                    if (screenShotPath == null || path.startsWith("/") || path.substring(1, 1).equals(":")) {
                        outputPath = path;
                    } else {
                        outputPath = screenShotPath + (screenShotPath.endsWith("/") ? "" : "/") + path;
                    }
                    System.out.println(screenshot.getAbsolutePath() + " -> " + path);
                    FileUtils.moveFile(screenshot, new File(outputPath));
                }
                return;
            }
            System.out.println();
            throw new Exception("screenshot argument should be a path");
        }
    }

    if (functions.containsKey(cmd)) {
        executeFunction(cmd, file, tokenizer, script);
        return;
    }

    if (null == driver) {
        throw new Exception("browser start must be used before attempt to interract with the browser");
    }

    System.out.println();
    throw new Exception("unrecognised command, " + cmd);
}

From source file:com.sat.spvgt.utils.selenium.SeleniumUtilities.java

License:Open Source License

/**
 * Nvigate to URL.//from  w  w w  .  ja  v  a 2  s. co  m
 * 
 * @param url
 *            the url
 */
public static void navigateToUrl(String url) {
    driver.get(url);
    String browser = miscValidate.readsystemvariable("browser");
    if (browser.equals("IE")) {
        WebDriverWait wait = new WebDriverWait(driver, 10);
        WebElement ele = wait.until(ExpectedConditions.elementToBeClickable(
                driver.findElement(By.linkText("Continue to this website (not recommended)."))));
        ele.click();
    }
    // driver.get(driver.getCurrentUrl());
}