• selenium fluentwait java实例


    本文转自:http://www.programcreek.com/java-api-examples/index.php?api=org.openqa.selenium.support.ui.FluentWait

    java代码实例org.openqa.selenium.support.ui.fluentwait
    以下是票数最高的例子展示了如何使用org.openqa.selenium.support.ui.fluentwait。这些示例是从开放源代码项目中提取的。

    Example 1
    Project: abmash   File: WaitFor.java View source code	7 votes	vote down vote up
    /**
    	 * Waits until element is found. Useful for waiting for an AJAX call to complete.
    	 * 
    	 * @param query the element query
    	 * @throws TimeoutException
    	 */
    	public void query(Query query) throws TimeoutException {
    //		WebDriverWait wait = new WebDriverWait(browser.getWebDriver(), timeout);
    		FluentWait<WebDriver> wait = new FluentWait<WebDriver>(browser.getWebDriver())
    	       .withTimeout(timeout, TimeUnit.SECONDS)
    	       .pollingEvery(500, TimeUnit.MILLISECONDS);
    		
    		// start waiting for given element
    		wait.until(new ElementWaitCondition(browser, query));
    	}
      
    
     
    Example 2
    Project: seauto   File: HtmlView.java View source code	7 votes	vote down vote up
    /**
     * Waits for an element to appear on the page before returning. Example:
     * WebElement waitElement =
     * fluentWait(By.cssSelector(div[class='someClass']));
     * 
     * @param locator
     * @return
     */
    protected WebElement waitForElementToAppear(final By locator)
    {
      Wait<WebDriver> wait = new FluentWait<WebDriver>(webDriver).withTimeout(30, TimeUnit.SECONDS).pollingEvery(5, TimeUnit.SECONDS).ignoring(NoSuchElementException.class);
    
      WebElement element = null;
      try {
        element = wait.until(new Function<WebDriver, WebElement>() {
    
          @Override
          public WebElement apply(WebDriver driver)
          {
            return driver.findElement(locator);
          }
        });
      }
      catch (TimeoutException e) {
        try {
          // I want the error message on what element was not found
          webDriver.findElement(locator);
        }
        catch (NoSuchElementException renamedErrorOutput) {
          // print that error message
          renamedErrorOutput.addSuppressed(e);
          // throw new
          // NoSuchElementException("Timeout reached when waiting for element to be found!"
          // + e.getMessage(), correctErrorOutput);
          throw renamedErrorOutput;
        }
        e.addSuppressed(e);
        throw new NoSuchElementException("Timeout reached when searching for element!", e);
      }
    
      return element;
    }
     
    Example 3
    Project: records-management   File: BrowseList.java View source code	7 votes	vote down vote up
    /**
     * Wait for all the expected rows to be there
     */
    private void waitForRows()
    {
        // get the number of expected items
        int itemCount = getItemCount();
        if (itemCount != 0)
        {
            // wait predicate
            Predicate<WebDriver> waitForRows = (w) ->
            {
                List<WebElement> rows = w.findElements(rowsSelector);
                return (itemCount == rows.size());
            };
            
            // wait until we have the expected number of rows
            new FluentWait<WebDriver>(Utils.getWebDriver())
                .withTimeout(10, TimeUnit.SECONDS)
                .pollingEvery(1, TimeUnit.SECONDS)
                .until(waitForRows); 
        }        
    }
      
    
     
    Example 4
    Project: automation-test-engine   File: AbstractElementFind.java View source code	6 votes	vote down vote up
    /**
     * Creates the wait.
     *
     * @param driver
     *            the driver
     */
    public void createWait(WebDriver driver) {
    	wait = new FluentWait<WebDriver>(driver)
    			.withTimeout(30, TimeUnit.SECONDS)
    			.pollingEvery(5, TimeUnit.SECONDS)
    			.ignoring(NoSuchElementException.class);
    }
     
    Example 5
    Project: thucydides   File: WhenTakingLargeScreenshots.java View source code	6 votes	vote down vote up
    private void waitUntilFileIsWritten(File screenshotFile) {
        Wait<File> wait = new FluentWait<File>(screenshotFile)
                .withTimeout(10, TimeUnit.SECONDS)
                .pollingEvery(250, TimeUnit.MILLISECONDS);
    
        wait.until(new Function<File, Boolean>() {
            public Boolean apply(File file) {
                return file.exists();
            }
        });
    }
     
    Example 6
    Project: vaadin-for-heroku   File: SessionTestPage.java View source code	6 votes	vote down vote up
    public SessionTestPage(final WebDriver driver) {
        this.driver = driver;
        wait = new FluentWait<WebDriver>(driver).withTimeout(1, TimeUnit.SECONDS)
                .ignoring(NoSuchElementException.class,
                        ElementNotFoundException.class);
    
    }
      
    
     
    Example 7
    Project: seleniumQuery   File: SeleniumQueryFluentWait.java View source code	6 votes	vote down vote up
    /**
     * @since 0.9.0
     */
    private <T> T fluentWait(SeleniumQueryObject seleniumQueryObject, Function<By, T> function, String reason) {
    	try {
    		return new FluentWait<>(seleniumQueryObject.getBy())
    						.withTimeout(waitUntilTimeout, TimeUnit.MILLISECONDS)
    							.pollingEvery(waitUntilPollingInterval, TimeUnit.MILLISECONDS)
    								.ignoring(StaleElementReferenceException.class)
    									.ignoring(NoSuchElementException.class)
    										.until(function);
    	} catch (TimeoutException sourceException) {
    		throw new SeleniumQueryTimeoutException(sourceException, seleniumQueryObject, reason);
    	}
    }
     
    Example 8
    Project: objectfabric   File: Selenium.java View source code	6 votes	vote down vote up
    private WebElement fluentWait(final By locator) {
        Wait<WebDriver> wait = new FluentWait<WebDriver>(_driver) //
                .withTimeout(5, TimeUnit.SECONDS) //
                .pollingEvery(100, TimeUnit.MILLISECONDS) //
                .ignoring(NoSuchElementException.class);
    
        WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
    
            public WebElement apply(WebDriver driver) {
                return driver.findElement(locator);
            }
        });
    
        return foo;
    }
     
    Example 9
    Project: redsniff   File: RedsniffWebDriverTester.java View source code	6 votes	vote down vote up
    /**
        * Wait until the supplied {@link FindingExpectation} becomes satisfied, or throw a {@link TimeoutException}
        * , using the supplied {@link FluentWait} 
        * This should only be done using a wait obtained by calling {@link #waiting()} to ensure the correct arguments are passed.
        * 
        * @param expectation
        * @param wait
        * @return
        */
    public <T, E, Q extends TypedQuantity<E, T>> T waitFor(
    		 final FindingExpectation<E, Q, SearchContext> expectation,	FluentWait<WebDriver> wait) {
    	try {
    		return new Waiter(wait).waitFor(expectation);
    	}
    	catch(FindingExpectationTimeoutException e){
    		//do a final check to get the message unoptimized
    		ExpectationCheckResult<E, Q> resultOfChecking = checker.resultOfChecking(expectation);
    		String reason;
    		if(resultOfChecking.meetsExpectation())
    			reason = "Expectation met only just after timeout.  At timeout was:
    " + e.getReason();
    		else {
    			reason = resultOfChecking.toString();
    			//if still not found first check there isn't a page error or something
    			defaultingChecker().assertNoUltimateCauseWhile(newDescription().appendText("expecting ").appendDescriptionOf(expectation));
    		}
    		throw new FindingExpectationTimeoutException(e.getOriginalMessage(), reason, e);
    	}
    }
     
    Example 10
    Project: yatol   File: AbstractWebFixture.java View source code	6 votes	vote down vote up
    /**
     * Searches for a given text on the page.
     * 
     * @param text
     *            to be searched for
     * @return {@code true} if the {@code text} is present on the page,
     *         {@code false} otherwise
     */
    public boolean checkTextIsPresentOnPage(final String text) {
    	// waitForPage();
    	try {
    		int interval = (int) Math.floor(Math.sqrt(timeout));
    		Wait<WebDriver> wait = new FluentWait<WebDriver>(webDriver).withTimeout(timeout, TimeUnit.SECONDS)
    				.pollingEvery(interval, TimeUnit.SECONDS)
    				.ignoring(NoSuchElementException.class, StaleElementReferenceException.class);
    		return wait.until(new ExpectedCondition<Boolean>() {
    
    			@Override
    			public Boolean apply(WebDriver driver) {
    				String source = webDriver.getPageSource();
    				source = source.replaceFirst("(?i:<HEAD[^>]*>[\s\S]*</HEAD>)", "");
    				return source.contains(text.trim());
    			}
    		});
    	} catch (Exception e) {
    		return false;
    	}
    }
     
    Example 11
    Project: seleniumcapsules   File: TicketflyTest.java View source code	6 votes	vote down vote up
    @Test
    public void changeLocationUsingExplicitWaitLambda() {
        WebDriver driver = new ChromeDriver();
        driver.get("http://www.ticketfly.com");
        driver.findElement(linkText("change location")).click();
    
        WebDriverWait webDriverWait = new WebDriverWait(driver, 5);
    
        WebElement location = webDriverWait.until(new Function<WebDriver, WebElement>() {
            @Override
            public WebElement apply(WebDriver driver) {
                return driver.findElement(By.id("location"));
            }
        });
    
        FluentWait<WebElement> webElementWait
                = new FluentWait<WebElement>(location)
                .withTimeout(30, SECONDS)
                .ignoring(NoSuchElementException.class);
        WebElement canada = webElementWait.until(new Function<WebElement, WebElement>() {
            @Override
            public WebElement apply(WebElement element) {
                return location.findElement(linkText("CANADA"));
            }
        });
        canada.click();
        WebElement allCanada = webElementWait.until(new Function<WebElement, WebElement>() {
            @Override
            public WebElement apply(WebElement element) {
                return location.findElement(linkText("Ontario"));
            }
        });
        allCanada.click();
        assertEquals(0, driver.findElements(linkText("Ontario")).size());
        assertEquals("Ontario", driver
                .findElement(By.xpath("//div[@class='tools']/descendant::strong")).getText());
    }
     
    Example 12
    Project: nuxeo-distribution   File: Select2WidgetElement.java View source code	6 votes	vote down vote up
    /**
     * Do a wait on the select2 field.
     *
     * @throws TimeoutException
     *
     * @since 6.0
     */
    private void waitSelect2()
            throws TimeoutException {
        Wait<WebElement> wait = new FluentWait<WebElement>(
                !mutliple ? driver.findElement(By.xpath(S2_SINGLE_INPUT_XPATH))
                        : element.findElement(By.xpath(S2_MULTIPLE_INPUT_XPATH))).withTimeout(
                SELECT2_LOADING_TIMEOUT,
                TimeUnit.SECONDS).pollingEvery(
                100,
                TimeUnit.MILLISECONDS).ignoring(
                NoSuchElementException.class);
        Function<WebElement, Boolean> s2WaitFunction = new Select2Wait();
        wait.until(s2WaitFunction);
    }
     
    Example 13
    Project: gxt-driver   File: Tree.java View source code	6 votes	vote down vote up
    public void waitForLoaded(long duration, TimeUnit unit) {
    	new FluentWait<WebDriver>(getDriver())
    			.withTimeout(duration, unit)
    			.ignoring(NotFoundException.class)
    			.until(new Predicate<WebDriver>() {
    				@Override
    				public boolean apply(WebDriver input) {
    					return !methods.isLoading(getWidgetElement(), getElement());
    				}
    			});
    }
     
    Example 14
    Project: gwt-driver   File: GwtWidgetFinder.java View source code	6 votes	vote down vote up
    public W waitFor(long duration, TimeUnit unit) {
    	return new FluentWait<WebDriver>(driver)
    			.withTimeout(duration, unit)
    			.ignoring(NotFoundException.class)
    			.until(new Function<WebDriver, W>() {
    		@Override
    		public W apply(WebDriver webDriver) {
    			return done();
    		}
    	});
    }
     
    Example 15
    Project: nuxeo   File: Select2WidgetElement.java View source code	6 votes	vote down vote up
    /**
     * Do a wait on the select2 field.
     *
     * @throws TimeoutException
     * @since 6.0
     */
    private void waitSelect2() throws TimeoutException {
        Wait<WebElement> wait = new FluentWait<WebElement>(
                !mutliple ? driver.findElement(By.xpath(S2_SINGLE_INPUT_XPATH))
                        : element.findElement(By.xpath(S2_MULTIPLE_INPUT_XPATH))).withTimeout(SELECT2_LOADING_TIMEOUT,
                                TimeUnit.SECONDS).pollingEvery(100, TimeUnit.MILLISECONDS).ignoring(
                                        NoSuchElementException.class);
        Function<WebElement, Boolean> s2WaitFunction = new Select2Wait();
        wait.until(s2WaitFunction);
    }
     
    Example 16
    Project: selenium-addon   File: SeleniumActions.java View source code	6 votes	vote down vote up
    /**
     * Clicks the button located at the given table at the given row and column. It additionally expects it to be secured with a
     * ConfirmDia?og (https://vaadin.com/directory#addon/confirmdialog).
     */
    public void clickTableButtonWithConfirmation(String tableName, int row, int col) {
        clickTableButton(tableName, row, col);
        ConfirmDialogPO popUpWindowPO = new ConfirmDialogPO(driver);
        popUpWindowPO.clickOKButton();
        FluentWait<WebDriver> wait = new WebDriverWait(driver, WaitConditions.LONG_WAIT_SEC, WaitConditions.SHORT_SLEEP_MS)
                .ignoring(StaleElementReferenceException.class);
        wait.until(new ExpectedCondition<Boolean>() {
    
            @Override
            public Boolean apply(WebDriver driver) {
                List<WebElement> findElements = driver.findElements(By.xpath("//div[contains(@class, 'v-window ')]"));
                return findElements.size() == 0;
            }
        });
        WaitConditions.waitForShortTime();
    }
     
    Example 17
    Project: constellation   File: CstlClientTestCase.java View source code	5 votes	vote down vote up
    /**
         * test wms creation page navigation
         */
    //    @Test
    //    @RunAsClient
        public void testCreateWMS() {
            driver.get(deploymentURL.toString() + "webservices");
            WebElement createService = driver.findElement(By.id("createservice"));
            assertNotNull(createService);
    
            //wms button test visibility
            WebElement wmschoice = driver.findElement(By.id("wmschoice"));
            assertFalse(wmschoice.isDisplayed());
            createService.click();
            assertTrue(wmschoice.isDisplayed());
    
            //go to form first page
            wmschoice.click();
    
            //Test visibility parts.
            WebElement description = driver.findElement(By.id("description"));
            final WebElement metadata = driver.findElement(By.id("metadata"));
            Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
                    .withTimeout(30, TimeUnit.SECONDS)
                    .pollingEvery(5, TimeUnit.SECONDS)
                    .ignoring(NoSuchElementException.class);
    
            wait.until(new Function<WebDriver, Boolean>() {
                @Override
                public Boolean apply(org.openqa.selenium.WebDriver webDriver) {
                    return metadata.isDisplayed()==false;
                }
            });
    
            assertTrue(description.isDisplayed());
            assertFalse(metadata.isDisplayed());
    
            //add forms data
            WebElement createtionWmsForm = driver.findElement(By.tagName("form"));
            createtionWmsForm.findElement(By.id("name")).sendKeys("serviceName");
            createtionWmsForm.findElement(By.id("identifier")).sendKeys("serviceIdentifier");
            createtionWmsForm.findElement(By.id("keywords")).sendKeys("service keywords");
            createtionWmsForm.findElement(By.id("inputDescription")).sendKeys("service Description");
            createtionWmsForm.findElement(By.id("inputDescription")).sendKeys("service Description");
            createtionWmsForm.findElement(By.id("v130")).click();
    
            driver.findElement(By.id("nextButton")).click();
    
            new WebDriverWait(driver, 20).until(new ExpectedCondition<Object>() {
                @Override
                public Object apply(org.openqa.selenium.WebDriver webDriver) {
                    if(webDriver.findElement(By.id("contactName")).isDisplayed())
                        return webDriver.findElement(By.id("contactName"));
                    else return null;
                }
            });
            // contact information & address
            createtionWmsForm.findElement(By.id("contactName")).sendKeys("contact Name");
            createtionWmsForm.findElement(By.id("contactOrganisation")).sendKeys("contact Organisation");
            createtionWmsForm.findElement(By.id("contactPosition")).sendKeys("contact position");
            createtionWmsForm.findElement(By.id("contactPhone")).sendKeys("contact Phone");
            createtionWmsForm.findElement(By.id("contactFax")).sendKeys("contact Fax");
            createtionWmsForm.findElement(By.id("contactEmail")).sendKeys("contact eMail");
            createtionWmsForm.findElement(By.id("contactAddress")).sendKeys("contact Adress");
            createtionWmsForm.findElement(By.id("contactCity")).sendKeys("contact City");
            createtionWmsForm.findElement(By.id("contactState")).sendKeys("contact State");
            createtionWmsForm.findElement(By.id("contactPostcode")).sendKeys("contact PostCode");
            createtionWmsForm.findElement(By.id("contactCountry")).sendKeys("contact Country");
    
            //constraint
            createtionWmsForm.findElement(By.id("fees")).sendKeys("fees");
            createtionWmsForm.findElement(By.id("accessConstraints")).sendKeys("access Constraint");
            createtionWmsForm.findElement(By.id("layerLimit")).sendKeys("layer Limit");
            createtionWmsForm.findElement(By.id("maxWidth")).sendKeys("max Width");
            createtionWmsForm.findElement(By.id("maxHeight")).sendKeys("max Height");
            createtionWmsForm.submit();
    
        }
     
    Example 18
    Project: NYU-Bobst-Library-Reservation-Automator-Java   File: Automator.java View source code	5 votes	vote down vote up
    /**
     * Main function to run the Automator
     * @param args Allows 1 argument for the file name of the user logins in .csv format
     */
    public static void main(String[] args)
    {
    	// Turns off annoying htmlunit warnings
    	java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(java.util.logging.Level.OFF);
    
    	// Setting inheritance stuff
    	Properties settings = new Properties();
    	InputStream input = null;
    
    	// Settings variables to be changed
    	int timeDelta = 90;
    	String description = "NYU Phi Kappa Sigma Study Session";
    	String floorNumber = "LL1";
    	String roomNumber = "20";
    	String userLoginsFilePath = "userLogins.csv";
    
    	try
    	{
    		input = new FileInputStream("settings");
    		settings.load(input);
    
    		// Initializes each value from the defaults to the values in the settings file
    		timeDelta = Integer.parseInt(settings.getProperty("timeDelta"));
    		description = settings.getProperty("description");
    		floorNumber = settings.getProperty("floorNumber");
    		roomNumber = settings.getProperty("roomNumber");
    		userLoginsFilePath = settings.getProperty("userLoginFile");
    	}
    	catch (IOException ex)
    	{System.err.println("Settings file could not be read correctly");}
    	finally
    	{
    		if (input != null)
    		{
    			try
    			{input.close();}
    			catch (IOException e)
    			{System.err.println("Error trying to close stream from settings file");}
    		}
    	}
    
    	// Gets the reservation date only once at the start
    	LocalDate currentDate = LocalDate.now();
    	LocalDate reservationDate = currentDate.plusDays(timeDelta);
    
    	// Date in string format
    	String reservationYear = Integer.toString(reservationDate.getYear());
    	String reservationMonth = "";
    
    	try
    	{reservationMonth = toMonth(Integer.toString(reservationDate.getMonthValue()));}
    	catch (MonthException e)
    	{System.out.println(e.getMessage());}
    
    	String reservationDay = Integer.toString(reservationDate.getDayOfMonth());
    
    	// Logging capability stuff
    	File logs = null;
    
    	// Error logging
    	PrintStream pErr = null;
    	FileOutputStream fErr = null;
    	File errors = null;
    
    	// Status logging
    	PrintStream pOut = null;
    	FileOutputStream fOut = null;
    	File status = null;
    
    	try
    	{
    		// Creates the directory hierarchy
    		logs = new File("logs");
    		if (!logs.isDirectory())
    			logs.mkdir();
    		status = new File("logs/status");
    		if (!status.isDirectory())
    			status.mkdir();
    		errors = new File("logs/errors");
    		if (!errors.isDirectory())
    			errors.mkdir();
    
    		fOut = new FileOutputStream(
    				"logs/status/" + reservationDate.toString() + ".status");
    		fErr = new FileOutputStream(
    				"logs/errors/" + reservationDate.toString() + ".err");
    		pOut = new PrintStream(fOut);
    		pErr = new PrintStream(fErr);
    		System.setOut(pOut);
    		System.setErr(pErr);
    	}
    	catch (FileNotFoundException ex)
    	{System.err.println("Couldn't find the logging file");}
    
    	// Checks for user logins .csv file existence
    	File userLogins = new File(userLoginsFilePath);
    
    	try
    	{
    		if (!userLogins.exists() || (userLogins.isDirectory()))
    			throw new IOException("userLogins.csv does not exist, or is a directory");
    	}
    	catch (IOException e)
    	{System.err.println(e.getMessage());}
    
    	// Builds an array of users based off of .csv
    	// Opens file stream
    	FileReader fr = null;
    	BufferedReader br = null;
    	StringTokenizer st = null;
    	ArrayList<User> users = new ArrayList<User>();
    	try {
    		fr = new FileReader(userLogins);
    		br = new BufferedReader(fr);
    		boolean lineSkip = true;
    
    		for (String line; (line = br.readLine()) != null; )
    		{
    			if (lineSkip)
    				lineSkip = false;
    			else
    			{
    				boolean timestampSkip = true;
    				st = new StringTokenizer(line, ",");
    				while (st.hasMoreTokens())
    				{
    					// Advances past the timeStamp
    					if (timestampSkip)
    					{
    						timestampSkip = false;
    						st.nextToken();
    					}
    					else
    					{
    						String username = st.nextToken();
    						String password = st.nextToken();
    
    						// Advances past the years until graduation
    						while (st.hasMoreTokens())
    							st.nextToken();
    						users.add(new User(username, password));
    					}
    				} // End of while loop
    			} // End of else
    		} // End of the for loop
    	} // End of the try block
    	catch (IOException e1)
    	{System.err.println("File could not be found");}
    	finally
    	{
    		try
    		{
    			fr.close();
    			br.close();
    		}
    		catch (IOException e)
    		{System.err.println("File error while trying to close file");}
    	}
    
    	// Start of going through the registration with each user
    	for (int i = 0; i < users.size(); ++i)
    	{
    		// Resets the AM at the end of the loop, since it's a static variable
    		AM_PM = true;
    
    		// Builds a browser connection
    		WebDriver browser = new FirefoxDriver();
    		browser.manage().window().maximize();
    
    		//HtmlUnitDriver browser = new HtmlUnitDriver(BrowserVersion.CHROME);
    		//browser.setJavascriptEnabled(true);
    
    		try
    		{
    			// Starts automation for user
    			System.out.println("User number: " + i + " status: starting");
    
    			browser.get("https://login.library.nyu.edu/pds?func=load-login&institute=NYU&calling_system=https:"
    					+ "login.library.nyu.edu&url=https%3A%2F%2Frooms.library.nyu.edu%2Fvalidate%3Freturn_url%3Dhttps"
    					+ "%253A%252F%252Frooms.library.nyu.edu%252F%26https%3A%2F%2Flogin.library.nyu.edu_action%3Dnew%2"
    					+ "6https%3A%2F%2Flogin.library.nyu.edu_controller%3Duser_sessions");
    
    			// Sleep until the div we want is visible or 15 seconds is over
    			FluentWait<WebDriver> fluentWait = new FluentWait<WebDriver>(browser)
    					.withTimeout(20, TimeUnit.SECONDS)
    					.pollingEvery(500, TimeUnit.MILLISECONDS)
    					.ignoring(NoSuchElementException.class);
    
    			fluentWait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@id='shibboleth']")));
    
    			browser.findElement(By.xpath("//div[@id='shibboleth']/p[1]/a")).click();
    
    			fluentWait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//form[@id='login']")));
    
    			// Now we're at the login page
    			WebElement username = browser.findElement(By.xpath("//form[@id='login']/input[1]"));
    			WebElement password = browser.findElement(By.xpath("//form[@id='login']/input[2]"));
    
    			// Signs into the bobst reserve with the user's username and password
    			username.sendKeys(users.get(i).getUsername());
    			password.sendKeys(users.get(i).getPassword()); 
    			browser.findElement(By.xpath("//form[@id='login']/input[3]")).click();
    
    			if (browser.getCurrentUrl().equals("https://shibboleth.nyu.edu:443/idp/Authn/UserPassword") ||
    					(browser.getCurrentUrl().equals("https://shibboleth.nyu.edu/idp/Authn/UserPassword")))
    				throw new InvalidLoginException("User " + i + " had invalid login credentials");
    
    			// START OF FUCKING AROUND WITH THE DATEPICKER
    			// Error checking that rooms.library.nyu.edu pops up
    			int count = 0;
    			while ((!browser.getCurrentUrl().equals("https://rooms.library.nyu.edu/")) && (count < 5))
    			{
    				browser.navigate().refresh();
    				Thread.sleep(5000);
    				fluentWait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@class='well well-sm']")));
    				++count;
    			}
    
    			browser.findElement(By.xpath(
    					"//form[@class='form-horizontal']/div[@class='well well-sm']" + 
    							"/div[@class='form-group has-feedback']/div[@class='col-sm-6']/input[1]"
    					)).click();
    
    			Thread.sleep(5000);
    
    			// Checks the month and year, utilizes a wait for the year for the form to pop up
    			WebElement datePickerYear = fluentWait.until(
    					ExpectedConditions.presenceOfElementLocated(By.xpath(
    							"//div[@id='ui-datepicker-div']/div[@class='ui-datepicker-group ui-datepicker-group-first']/" + 
    									"div[@class='ui-datepicker-header ui-widget-header ui-helper-clearfix ui-corner-left']/" + 
    									"div[@class='ui-datepicker-title']/span[@class='ui-datepicker-year']"
    							)));
    
    			String datePickerYearText = datePickerYear.getText();
    
    			WebElement datePickerMonth = browser.findElement(By.xpath(
    					"//div[@id='ui-datepicker-div']/div[@class='ui-datepicker-group ui-datepicker-group-first']/" + 
    							"div[@class='ui-datepicker-header ui-widget-header ui-helper-clearfix ui-corner-left']/" +
    							"div[@class='ui-datepicker-title']/span[@class='ui-datepicker-month']"
    					));
    			String datePickerMonthText = datePickerMonth.getText();
    
    			// Alters year
    			while (!datePickerYearText.equals(reservationYear))
    			{
    				// Right clicks the month until it is the correct year
    				browser.findElement(By.className("ui-icon-circle-triangle-e")).click();
    
    				// Updates the datepicker year
    				datePickerYear = browser.findElement(By.xpath(
    						"//div[@id='ui-datepicker-div']/div[@class='ui-datepicker-group ui-datepicker-group-first']/" + 
    								"div[@class='ui-datepicker-header ui-widget-header ui-helper-clearfix ui-corner-left']/" + 
    								"div[@class='ui-datepicker-title']/span[@class='ui-datepicker-year']"
    						));
    				datePickerYearText = datePickerYear.getText();
    			}
    
    			// ALters month
    			while (!datePickerMonthText.equals(reservationMonth))
    			{
    				// Right clicks the month until it is the correct month
    				browser.findElement(By.className("ui-icon-circle-triangle-e")).click();
    
    				// Updates the datepicker month
    				datePickerMonth = browser.findElement(By.xpath(
    						"//div[@id='ui-datepicker-div']/div[@class='ui-datepicker-group ui-datepicker-group-first']/" + 
    								"div[@class='ui-datepicker-header ui-widget-header ui-helper-clearfix ui-corner-left']/" +
    								"div[@class='ui-datepicker-title']/span[@class='ui-datepicker-month']"
    						));
    				datePickerMonthText = datePickerMonth.getText();
    			}
    
    			// At this point, we are on the correct year & month. Now we select the date
    			browser.findElement(By.linkText(reservationDay)).click();
    
    			// END OF THE FUCKING DATEPICKER
    
    			// Selects the start time
    			int timeStart = getTime(i);
    
    			Select reservationHour = new Select(browser.findElement(By.cssSelector("select#reservation_hour")));
    			reservationHour.selectByValue(Integer.toString(timeStart));
    
    			Select reservationMinute = new Select(browser.findElement(By.cssSelector("select#reservation_minute")));
    			reservationMinute.selectByValue("0");
    
    			// Selects AM/PM
    			Select reservationAMPM = new Select(browser.findElement(By.cssSelector("select#reservation_ampm")));
    			if (AM_PM)
    				reservationAMPM.selectByValue("am");
    			else
    				reservationAMPM.selectByValue("pm");
    
    			// Selects the time length
    			Select timeLength = new Select(browser.findElement(By.cssSelector("select#reservation_how_long")));
    			timeLength.selectByValue("120");
    
    			// Generates the room/time picker
    			browser.findElement(By.xpath("//button[@id='generate_grid']")).click();
    
    			WebElement alert = null;
    			// Checks if the user has already reserved a room for the day
    			try
    			{
    				alert = fluentWait.until(
    						ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@class='alert alert-danger']")));
    			}
    			catch (TimeoutException e)
    			{
    				// Does nothing, since it's a good thing
    			}
    			if (alert != null)
    				throw new ReservationException("The user number: " + i + " has already reserved a room for today");
    
    			// Waits for the reservation to pop up
    			fluentWait.until(
    					ExpectedConditions.presenceOfElementLocated(
    							By.xpath("//div[@class='modal-content']/div[@class='modal-body']/div[@class='modal-body-content']")
    							));
    
    			WebElement descriptionElement = fluentWait.until(
    					ExpectedConditions.presenceOfElementLocated(By.id("reservation_title")));
    			descriptionElement.sendKeys(description);
    
    			// Fills in the duplicate email for the booking
    			WebElement duplicateEmailElement = browser.findElement(By.id("reservation_cc"));
    			duplicateEmailElement.sendKeys(users.get(i).getEmailDuplicate());
    
    			// Selects the row on the room picker
    			String roomText = "Bobst " + floorNumber + "-" + roomNumber;
    
    			// Locates the room
    			WebElement divFind = browser.findElement(
    					By.xpath(
    							"//form[@id='new_reservation']/table[@id='availability_grid_table']/tbody/tr[contains(., '" + roomText + "')]")
    					);
    
    			WebElement timeSlot = null;
    
    			// Tries to get the next best time if it doesn't work
    			try
    			{
    				timeSlot = divFind.findElement(By.xpath("td[@class='timeslot timeslot_available timeslot_preferred']"));
    			}
    			catch (NoSuchElementException e)
    			{
    				System.err.println("The timeslot was already taken for user: " + i + ", taking next best time");
    				boolean found = false;
    
    				// Continuously clicks the next button and checks until a time is found
    				while (found == false)
    				{
    					try
    					{
    						// Clicks the button once
    						browser.findElement(By.xpath("//div[@class='rebuild_grid rebuild_grid_next']")).click();
    
    						// Rechecks to find the timeSlot
    						timeSlot = divFind.findElement(By.xpath("td[@class='timeslot timeslot_available timeslot_preferred']"));
    
    						// If it gets to this point, the timeslot is found, sets found = true
    						found = true;
    					}
    					catch (NoSuchElementException ex)
    					{
    						// Still didn't find an available timeslot, continues search
    					}	
    				} // End of while loop
    			} // End of finding a time if original preference could not be found
    
    			timeSlot.click();
    
    			// Submits
    			browser.findElement(By.xpath("//button[@class='btn btn-lg btn-primary']")).click();
    
    			// Waits a bit for confirmation to occur
    			FluentWait<WebDriver> buttonWait = new FluentWait<WebDriver>(browser)
    					.withTimeout(15, TimeUnit.SECONDS)
    					.pollingEvery(500, TimeUnit.MILLISECONDS)
    					.ignoring(NoSuchElementException.class);
    
    			buttonWait.until(
    					ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@class='alert alert-success']")));
    
    			// Final status update
    			System.out.println("User number " + i + " status: successful");
    
    			// Updates the dailyStatus log
    			String militaryTime = toMilitaryTime(i);
    			System.out.println(militaryTime + ": Reserved");
    			Thread.sleep(3000);
    		}
    		catch (UserNumberException e)
    		{
    			System.err.println(e.getMessage());
    			System.out.println("User number " + i + " status: failed");
    
    			// Updates the dailyStatus log
    			String militaryTime = toMilitaryTime(i);
    			System.out.println(militaryTime + ": Not Reserved");
    		}
    		catch(ReservationException e)
    		{
    			System.err.println(e.getMessage());
    			System.out.println("User number " + i + " status: failed");
    
    			// Updates the dailyStatus log
    			String militaryTime = toMilitaryTime(i);
    			System.out.println(militaryTime + ": Not Reserved");
    		}
    		catch(TimeoutException e)
    		{
    			System.err.println(e.getMessage());
    			System.out.println("User number " + i + " status: failed");
    
    			// Updates the dailyStatus log
    			String militaryTime = toMilitaryTime(i);
    			System.out.println(militaryTime + ": Not Reserved");
    		}
    		catch(InvalidLoginException e)
    		{
    			System.err.println(e.getMessage());
    			System.out.println("User number " + i + " status: failed");
    
    			// Updates the dailyStatus log
    			String militaryTime = toMilitaryTime(i);
    			System.out.println(militaryTime + ": Not Reserved");
    		}
    		catch (InterruptedException e)
    		{
    			System.err.println("Sleep at end was interrupted");
    			System.out.println("User number " + i + " status: failed");
    
    			// Updates the dailyStatus log
    			String militaryTime = toMilitaryTime(i);
    			System.out.println(militaryTime + ": Not Reserved");
    		}
    		catch (Exception e)
    		{
    			System.err.println("Shit, something happened that wasn't caught");
    			System.out.println("User number " + i + " status: failed");
    			e.printStackTrace();
    
    			// Updates the dailyStatus log
    			String militaryTime = toMilitaryTime(i);
    			System.out.println(militaryTime + ": Not Reserved");
    		}
    		finally
    		{
    			// Logs out
    			browser.get("https://rooms.library.nyu.edu/logout");
    			try
    			{Thread.sleep(10000);}
    			catch (InterruptedException e1)
    			{System.err.println("Something wrong when trying to sleep after logout");}
    
    			// Deletes cookies
    			browser.manage().deleteAllCookies();
    			browser.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    
    			// Closes the browser connection
    			browser.close();
    			System.out.println("Browser is now closed");
    			try {Thread.sleep(5000);}
    			catch (InterruptedException e)
    			{System.err.println("Sleep at end was interrupted");}
    		}
    	} //End of for loop
    
    	// Closes logging streams
    	if (pOut != null)
    		pOut.close();
    	if (pErr != null)
    		pErr.close();
    	if (fOut != null)
    	{
    		try
    		{fOut.close();}
    		catch (IOException e)
    		{System.err.println("File output logging stream had errors when closing");}
    	}
    	if (fErr != null)
    	{
    		try
    		{fErr.close();}
    		catch (IOException e)
    		{System.err.println("File output error stream had errors when closing");}
    	}
    }
    

      

  • 相关阅读:
    select2使用
    Jquery DataTables相关示例
    基于Cef内核的多店铺登录器(含源码)
    Navi.Soft31.产品.登录器(永久免费)
    基于JQuery EasyUI的WebMVC控件封装(含源码)
    EntityFrameWork实现部分字段获取和修改(含源码)
    基于Ado.Net的日志组件
    C#实现七牛云存储
    局域网内手机播放视频
    基于微软企业库的AOP组件(含源码)
  • 原文地址:https://www.cnblogs.com/lincj/p/7026179.html
Copyright © 2020-2023  润新知