Java tutorial
package com.sinet.gage.uitest.helper; import java.io.File; import java.text.DateFormat; import java.text.DateFormatSymbols; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.LocalFileDetector; import org.openqa.selenium.remote.RemoteWebElement; import org.openqa.selenium.support.ui.Select; import org.testng.Reporter; import org.testng.log4testng.Logger; /** * This is common helper class and can hold non application specific generic * methods * * @author Team Gage * */ public class CommonHelper { protected static Logger log = Logger.getLogger(CommonHelper.class); public static void sortAscendingWithIgnoreCase(List<String> list) { Collections.sort(list, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }); } public static void sortDescendingtWithIgnoreCase(List<String> list) { Collections.sort(list); Collections.sort(list, Collections.reverseOrder(String.CASE_INSENSITIVE_ORDER)); } public static void sortAscendingIntegerList(List<String> listSeats) { List<Integer> intList = new ArrayList<Integer>(); for (String o : listSeats) { intList.add(new Integer(o)); } Collections.sort(intList); log.info("Sorted :" + intList); } public static void sortDescendingIntegerList(List<String> listSeats) { List<Integer> intList = new ArrayList<Integer>(); for (String o : listSeats) { intList.add(new Integer(o)); } Collections.sort(intList); Collections.sort(intList, Collections.reverseOrder()); log.info("Sorted :" + intList); } public static void nap() { try { Thread.sleep(1000); } catch (Exception e) { log.info("interrupted "); } } public static String getPilotExpirationDate() { SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); Date today = new Date(); return sdf.format(new Date(today.getTime() + 90 * (1000 * 60 * 60 * 24))); } public static By getLocatorFormatInt(By locator, int index) { String xpath = String.format(locator.toString(), "" + index); String newXpath = xpath.substring(xpath.indexOf('/')); return By.xpath(newXpath); } public static By getLocatorFormatString(By locator, String sub) { String xpath = String.format(locator.toString(), "" + sub); String newXpath = xpath.substring(xpath.indexOf('/')); return By.xpath(newXpath); } public static int getTableColumnHeaderIndex(List<WebElement> webElements, String strColumnName) { int col = 1; for (WebElement ele : webElements) { if (ele.getText().trim().equals(strColumnName)) { return col; } col++; } return -1; } public static void selectDropDownValueByVisibleText(WebElement element, String strValue) { Select tempVal = new Select(element); tempVal.selectByVisibleText(strValue); } public static void selectDropDownValueByIndex(WebElement element, int strValue) { Select tempVal = new Select(element); tempVal.selectByIndex(strValue); } public static List<String> getAllDropDownValues(WebElement element) { Select tempVal = new Select(element); List<String> dropdownValues = new ArrayList<String>(); List<WebElement> dropdownOptions = new ArrayList<WebElement>(); dropdownOptions = tempVal.getOptions(); for (WebElement we : dropdownOptions) { dropdownValues.add(we.getText().trim()); } return dropdownValues; } public static String getFirstSelectedOptionFromDropDown(WebElement ele) { Select tempVal = new Select(ele); String strName = tempVal.getFirstSelectedOption().getText(); return strName; } public static String getTableColumnValue(int tableSize, List<String> lstStringNames, List<String> lstStringSeats, String licenseName) { String tableVal = ""; for (int i = 0; i < tableSize; i++) { if (lstStringNames.get(i).toString().equals(licenseName)) { tableVal = lstStringSeats.get(i).toString(); log.info(tableVal); break; } } return tableVal; } public static boolean compareLists(List<String> firstList, List<String> secondList) { boolean flag = false; if (firstList.size() == secondList.size()) { for (int counter = 0; counter < firstList.size(); counter++) { if (secondList.get(counter).equals(firstList.get(counter))) { log.info("Expected List value : " + secondList.get(counter) + " Expected List value : " + firstList.get(counter)); flag = true; } else { log.error("Fail : Expected List value : " + secondList.get(counter) + " Expected List value : " + firstList.get(counter)); flag = false; break; } } } else { flag = false; } return flag; } public static boolean compareMaps(Map<String, String> map1, Map<String, String> map2) { final Collection<String> allKeys = new HashSet<String>(); allKeys.addAll(map1.keySet()); allKeys.addAll(map2.keySet()); boolean result = false; for (final String key : allKeys) { if (map1.containsKey(key) == map2.containsKey(key) && map1.get(key).equals(map2.get(key))) { log.info("Key " + key + " value " + map2.containsKey(key)); result = true; } else { log.info("Fail : Key : " + key + " and value from map1 is : " + map2.containsKey(key) + ", Value from map2 : " + map1.containsKey(key)); result = false; break; } } return result; } public static String formatDateAsPerDB(String strDate, String fromFormat, String toFormat) { String format = ""; try { Date date = new SimpleDateFormat(fromFormat).parse(strDate); format = new SimpleDateFormat(toFormat).format(date); return format; } catch (Exception e) { return "None"; } } /** * This function generates random number * * @param digits * @return */ public static int generateRandomNumber() { Random rand = new Random(); int randNumber = 1; randNumber = rand.nextInt(100000); return randNumber; } /** * This function generates string of passed char of given length * * @param size,char * @return */ public static String generateStringAsPerGivenSize(int size, char ch) { final char[] array = new char[size]; Arrays.fill(array, ch); return new String(array); } /** * wait till web page is in ready state. * * @param driver The object of diver to perform wait. * */ public static void waitForAjax(WebDriver driver) { nap(); try { if (driver instanceof JavascriptExecutor) { JavascriptExecutor jsDriver = (JavascriptExecutor) driver; for (int i = 0; i < 30; i++) { boolean resultofAjaxWait = "complete" .equals(jsDriver.executeScript("return document.readyState")); Reporter.log("Ajax calls complete " + resultofAjaxWait); if (resultofAjaxWait) { break; } Thread.sleep(1000); } } else { Reporter.log("ERROR : Web driver: " + driver + " cannot execute javascript"); } } catch (InterruptedException e) { Reporter.log("ERROR : Interrupted Exception " + e.getMessage()); } } /** * Gets a new generated name which is sum of text+system date * * @param title * @return */ public static String getNewName(String title) { String newTitle = title + new SimpleDateFormat("MMddhhmmssSSS").format(new Date()).substring(0, 10); return newTitle; } /** * Convert List of elements to List of element text strings * * @param listOfElements list of elements * @return List of element text */ public static List<String> getTextFromElements(List<WebElement> listOfElements) { List<String> stringValues = new ArrayList<String>(); for (WebElement element : listOfElements) { if (!"".equals(element.getText().trim())) { stringValues.add(element.getText().trim()); } } return stringValues; } /** * Returns sorted list in ascending or descending order * * @param listToSort list of string to sort * @param isDescending order to sort(ascending or descending) * @return List of sorted string */ public static List<String> getSortedList(List<String> listToSort, boolean isDescending) { List<String> sortedList = new ArrayList<String>(listToSort); if (isDescending) { sortDescendingtWithIgnoreCase(sortedList); } else { sortAscendingWithIgnoreCase(sortedList); } return sortedList; } public static List<String> getSortedListInteger(List<String> listToSort, boolean isDescending) { List<String> sortedList = new ArrayList<String>(listToSort); if (isDescending) { sortDescendingIntegerList(sortedList); } else { sortAscendingIntegerList(sortedList); } return sortedList; } /** * Returns true if date matches the specified pattern * * @param date in string format * @param pattern to match * @return true/false */ public static boolean validateDateFormat(String date, String pattern) { String regex = pattern.replaceAll("\\w", "\\\\d").replace(".", "\\."); log.info("Regular expression: " + regex); if (!date.matches(regex)) { return false; } SimpleDateFormat sdf = new SimpleDateFormat(pattern); sdf.setLenient(false); try { sdf.parse(date); } catch (Exception e) { return false; } return true; } /** * Method used to upload a file * * @param element web element of file needs to be upload * @param filePath file path name of file needs to be upload * */ public static void fileUpload(WebElement element, String filePath, boolean isGrid) { try { // File file = new File( new File( "." ).getCanonicalPath() + filePath ); File file = new File(filePath); file.toURI(); if (isGrid) { ((RemoteWebElement) element).setFileDetector(new LocalFileDetector()); } element.sendKeys(file.getAbsolutePath()); // } catch ( IOException e ) { } catch (Exception e) { e.printStackTrace(); } } public static void sortDateInAscending(List<String> dateString, String pattern) { final String datePattern = pattern; Collections.sort(dateString, new Comparator<String>() { DateFormat format = new SimpleDateFormat(datePattern); @Override public int compare(String o1, String o2) { try { return format.parse(o1).compareTo(format.parse(o2)); } catch (ParseException e) { throw new IllegalArgumentException(e); } } }); } public static void sortDateInDescending(List<String> dateString, String pattern) { final String datePattern = pattern; Collections.sort(dateString, new Comparator<String>() { DateFormat format = new SimpleDateFormat(datePattern); @Override public int compare(String o1, String o2) { try { return format.parse(o2).compareTo(format.parse(o1)); } catch (ParseException e) { throw new IllegalArgumentException(e); } } }); } public static List<String> getSortedListDate(List<String> listToSort, String pattern, boolean isDescending) { List<String> sortedList = new ArrayList<String>(listToSort); if (isDescending) { sortDateInDescending(sortedList, pattern); } else { sortDateInAscending(sortedList, pattern); } return sortedList; } public static List<Integer> convertListOfStringsToInteger(List<String> listToConvert) { List<Integer> integerList = new ArrayList<Integer>(); for (String s : listToConvert) { integerList.add(Integer.valueOf(s)); } return integerList; } /** * Converts String date to Util Date * * @param pattern pattern of string date * @param date String date to convert * @return Util date */ public static Date convertStringDateToUtilDate(String pattern, String date) { DateFormat formatter = new SimpleDateFormat(pattern); try { return formatter.parse(date); } catch (ParseException e) { throw new IllegalArgumentException(e); } } /** * Converts Util Date to String date * * @param pattern pattern of Util date * @param date String date to convert * @return string date */ public static String convertUtilDateToStringDate(String pattern, Date date) { DateFormat formatter = new SimpleDateFormat(pattern); return formatter.format(date); } /** * Adds/Substract days to/from given date * * @param date Util date to add/substract * @param days number of days to add/substract * @param isAdd boolean value to add/substract * @return result date */ public static Date addOrSubstractDays(Date date, int days, boolean isAdd) { int noOfDays = days; if (!isAdd) { noOfDays = days * -1; } Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.DATE, noOfDays); return cal.getTime(); } /** * Get a diff between two dates * * @param date1 the oldest date * @param date2 the newest date * @param timeUnit the unit in which you want the diff(e.g. NANOSECONDS, * MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS) * @return the diff value, in the provided unit */ public static long getDateDiff(Date date1, Date date2, TimeUnit timeUnit) { long diffInMillies = date2.getTime() - date1.getTime(); return timeUnit.convert(diffInMillies, TimeUnit.MILLISECONDS); } /** * Get All selected options * * @param element select element * @return List of string, selected options */ public static List<String> getAllSelectedOptionsFromSelectBox(WebElement element) { Select selEle = new Select(element); return getTextFromElements(selEle.getAllSelectedOptions()); } /** * Select All options * * @param element select element * @param optionsText list of option text to select */ public static void selectOptionsByVisibleText(WebElement element, List<String> optionsText) { Select selEle = new Select(element); for (String option : optionsText) { selEle.selectByVisibleText(option); } } /** * Deselect All selected options * * @param element select element */ public static void deselectAllSelectedOptionsFromSelectBox(WebElement element) { new Select(element).deselectAll(); } /** * get date index for the given date * * @param date Util date * @return int date index */ public static int getDateIndexFromDate(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal.get(Calendar.DATE); } /** * get Month index from the given date * * @param date Util date * @return int month index */ public static int getMonthIndexFromDate(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal.get(Calendar.MONTH); } /** * get Month name from the given date * * @param date Util date * @return String month name */ public static String getMonthNameFromDate(Date date) { return new DateFormatSymbols().getMonths()[getMonthIndexFromDate(date)]; } /** * get Year from the given date * * @param date Util date * @return int YEAR */ public static int getYearFromDate(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal.get(Calendar.YEAR); } }