How to avoid StaleElementReferenceException - java

public long SearchHotel(String hotelname,String Provider,String CookieName) throws InterruptedException, ParseException{
long Day = 0;
WebDriver driver =new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(5000, TimeUnit.MILLISECONDS);
driver.get("url");
driver.manage().window().maximize();
driver.findElement(By.id("hc_f_id_where_1")).sendKeys(hotelname);
List<WebElement> HL = driver.findElements(By.id("ui-id-1"));
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.id("ui-id-1")));
String startDate = null;
String endDate = null;
Date d1,d2;
Calendar firstDate =null;
Calendar secondDate =null;
org.joda.time.DateTime dt1;
org.joda.time.DateTime dt2;
long diffInMillisec=0;
long diffInDays=0;
//DateTime dt2;
SimpleDateFormat dateFormat = null;
for (WebElement e : HL)
{
if(e.getText().contains(hotelname))
{
System.out.println("In IF");
driver.findElement(By.partialLinkText(hotelname)).click();
}
}
driver.findElement(By.id("HC_DateSelection_checkin_1")).click();
driver.findElement(By.cssSelector("img.ui-datepicker-trigger")).click();
WebElement dateWidget = driver.findElement(By.cssSelector("div.ui-datepicker-group.ui-datepicker-group-last table.ui-datepicker-calendar"));
List<WebElement> columns=dateWidget.findElements(By.tagName("td"));
for (WebElement cell : columns)
{
//System.out.println(cell.getText());
if(cell.getText().equals("7"))
{
cell.findElement(By.linkText("7")).click();
break;
}
}
driver.findElement(By.id("HC_DateSelection_checkout_1")).click();
driver.findElement(By.cssSelector("div#HC_DateSelection_checkout_1 img.ui-datepicker-trigger")).click();
WebElement datewidget1 = driver.findElement(By.cssSelector("div.ui-datepicker-group.ui-datepicker-group-first table.ui-datepicker-calendar"));
List<WebElement> columns1 = datewidget1.findElements(By.tagName("td"));
for (WebElement cell1 : columns1)
{
//System.out.println(cell1.getText());
if(cell1.getText().equals("11"))
{
cell1.findElement(By.linkText("11")).click();
break;
}
}
driver.findElement(By.className("hc_f_btn_v15")).click();
driver.findElement(By.className("hc_usi")).click();
System.out.println("Waiting");
WebElement HotelList=driver.findElement(By.cssSelector("table#hc_htl_pm_rates_content"));
List<WebElement> Hl=HotelList.findElements(By.tagName("tr"));
for (WebElement H : Hl) {
if(Provider.equals(H.getAttribute("data-providername"))){
System.out.println("Provider Name : "+H.getAttribute("data-providername").toString());
Wait<WebDriver> fwait = new FluentWait<WebDriver>(driver).withTimeout(30,TimeUnit.SECONDS).pollingEvery(5,TimeUnit.SECONDS).ignoring(StaleElementReferenceException.class);
fwait.until(ExpectedConditions.elementToBeClickable(H.findElement(By.tagName("a")))).click();
H.findElement(By.tagName("a")).click();
break;
}
}
Set<String> winHandles=driver.getWindowHandles();
for (String window : winHandles)
{
driver.switchTo().window(window);
}
wait.until(ExpectedConditions.visibilityOfElementLocated(By.tagName("h1")));
System.out.println("Page Title : "+driver.getTitle());
String curURL=driver.getCurrentUrl();
System.out.println("Current URL : "+curURL);
dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Set<Cookie> cookies = driver.manage().getCookies();
Iterator<Cookie> itr = cookies.iterator();
while (itr.hasNext())
{
Cookie c = itr.next();
System.out.println("-----Cookies Detail-----");
System.out.println("Cookie Name: " + c.getName() + "\n\tCookie Domain: " + c.getDomain() + "\n\tCookie Value: " + c.getValue() + "\n\tPath: " + c.getPath()+ "\n\tExpiry Date: " + c.getExpiry()+ "\n\tSecure: " + c.isSecure());
if(CookieName.equalsIgnoreCase(c.getName()))
{
System.out.println("Cookies Found : " +CookieName);
try
{
endDate = c.getExpiry().toString();
SimpleDateFormat format = new SimpleDateFormat("E MMM dd hh:mm:ss Z yyyy");
//SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
d1=format.parse(endDate);
System.out.println(d1);
d2=new Date();
startDate=d2.toString();
d2=format.parse(startDate);
System.out.println(d2);
dt1 = new org.joda.time.DateTime(d1);
dt2 = new org.joda.time.DateTime(d2);
Day=Days.daysBetween(dt2,dt1).getDays();
firstDate = Calendar.getInstance();
secondDate = Calendar.getInstance();
firstDate.setTime(d1);
secondDate.setTime(d2);
int month = firstDate.get(Calendar.MONTH)+1;
int dt = firstDate.get(Calendar.DATE);
int year = firstDate.get(Calendar.YEAR);
firstDate.set(year, month, dt);
System.out.println("First Dare "+dt+"/"+month+"/"+year);
int month2=secondDate.get(Calendar.MONTH)+1;
int dt22 = secondDate.get(Calendar.DATE);
int year2= secondDate.get(Calendar.YEAR);
secondDate.set(year2, month2, dt22);
System.out.println("Second Date "+dt22+"/"+month2+"/"+year2);
diffInMillisec = firstDate.getTimeInMillis() - secondDate.getTimeInMillis();
diffInDays = diffInMillisec / (24 * 60 * 60 * 1000);
System.out.println("DAYS : "+diffInDays);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
driver.quit();
return diffInDays;
}
getting Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up
Command duration or timeout: 5.50 seconds

Related

Get available days between two days in java

I am newly for java, and i want to build booking system and now i try to get available days between two days without booked days. but, however my code running bad.
this is my code
Connection connection = DBConnection.getInstance().getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * from A");
ResultSet executeQuery = preparedStatement.executeQuery();
while (executeQuery.next()) {
String refid = executeQuery.getString("REFID");
statDate = executeQuery.getDate("Start_date");
endDate = executeQuery.getDate("End_date");
System.out.println("ref no : " + refid + " statDate :" + statDate + " end date :" + endDate);
System.out.println("\n");
int month = statDate.getMonth();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, 1);
int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
//
for (int i = 1; i < maxDay; i++) {
cal.set(Calendar.DAY_OF_MONTH, i + 1);
String format = df.format(cal.getTime());
dateOfMonth.add(format);
addDays = addDays(statDate, 2);
if (df.format(cal.getTime()).equals("" + statDate) || df.format(cal.getTime()).equals("" + endDate)) {
//System.out.println(statDate + " is not available !");
System.out.println("---");
} else {
int bDays = endDate.getDate() - statDate.getDate();
//System.out.println(bDays);
//===========
List<DateTime> between = getDateRange(DateTime.parse(statDate.toString()), DateTime.parse(endDate.toString()));
for (DateTime dateTime : between) {
Date da = dateTime.toDate();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
dateOfBooked.add(sdf.format(da));
}
System.out.println(df.format(cal.getTime()));
}
}
System.out.println("\n");
}
this is my db script
insert into A values('1','ref1','2018-02-18','2018-02-25');
insert into A values('2','ref1','2018-03-10','2018-03-17');
insert into A values('3','ref1','2018-03-20','2018-03-27');
i try to get available days from thees booked days. how can i print only available days ?
output

how to convert multiple format of dates into only one format using java

from the database postgressql i'm getting date sometime date in different different forlamts like "2015-11-26 09:30:10","2015-11-26 09:30:10.080","2015-11-26 09:30:10.000" now i want to convert all format as only this format 22/01/2018 how to do in java.
try {
Date theDate1 = new Date("JAN 13,2014 09:15");
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
String temp = format1.format(theDate1);
System.out.println("Hello, World! " + temp);
} catch (Exception e {
System.out.println(e.toString());
}
i got output as Hello, World !13 / 01 / 2014 but when i tried
try {
Date theDate1 = new Date("2017-11-27 00:00:00");
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
String temp = format1.format(theDate1);
System.out.println("Hello, World! " + temp);
} catch (Exception e) {
System.out.println(e.toString());
}
then i got java.lang.IllegalArgumentExceptionhow to solve this problem
Try this
String text = "JAN 13,2014 09:15";
String patternst = "\\d\\d\\d\\d-\\d\\d-\\d\\d*";
Pattern pattern = Pattern.compile(patternst);
Matcher matcher = pattern.matcher(text);
String data = "";
while (matcher.find()) {
data = matcher.group(0);
}
try {
int year = Integer.parseInt(data.split("-")[0]);
int month = Integer.parseInt(data.split("-")[1]);
int day = Integer.parseInt(data.split("-")[2]);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, day);
Date theDate1 = cal.getTime();
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
String temp = format1.format(theDate1);
System.out.println("Hello, World! " + temp);
} catch (Exception e) {
Date theDate1 = new Date(text);
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
String temp = format1.format(theDate1);
System.out.println("Hello, World! " + temp);
}

How to get first and last date of weeks on basis of month and year in android

how to get first and last date of weeks on basis of month and year in android
ex:we pass month and year (March,2016) then i want all weeks just like
mar5- mar11,(sat to fri)
mar12- mar18,
mar19- mar25,
mar26-april01
please help me
Call this function to get results in a valid week pair list of given month of a year.
ex: getWeekStartEnd("December","2016");
Result: [
December3-December9,
December10-December16,
December17-December23,
December24-December30
]
List<String> getWeekStartEnd (String month , String year) {
List<String> validWeekPairs = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMMMM-yyyy");
String day = "01";
try {
Date date = sdf.parse(day + "-" + month + "-" + year);
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.setTime(date);
calendar.setFirstDayOfWeek(Calendar.SATURDAY);
List<String> startDayOfWeek = new ArrayList<>();
List<String> endDayOfWeek = new ArrayList<>();
int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
boolean isStartDaySet = false;
boolean hasLastDayOfWeek = true;
for (int currentDay = 01; currentDay <= daysInMonth; currentDay++) {
Date newDate = sdf.parse(currentDay + "-" + month + "-" + year);
calendar.setTime(newDate);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.SATURDAY) {
if (hasLastDayOfWeek) {
startDayOfWeek.add(month + String.valueOf(currentDay));
isStartDaySet = true;
hasLastDayOfWeek = false;
}
} else if (dayOfWeek == Calendar.FRIDAY) {
if (isStartDaySet) {
endDayOfWeek.add(month + String.valueOf(currentDay));
hasLastDayOfWeek = true;
}
}
}
for (int i = 0; i < endDayOfWeek.size(); i++) {
validWeekPairs.add(startDayOfWeek.get(i) + "-" + endDayOfWeek.get(i));
}
return validWeekPairs;
} catch (ParseException e) {
e.printStackTrace();
return validWeekPairs;
}catch (Exception e){
e.printStackTrace();
return validWeekPairs;
}
}
If you are using java.util.Date you can use the method getDay(). It returns Calendar constant, like Calendar.MONDAY.
You can pass the string as 02,2016
List<String> getWeekendsOftheMonth(String monthYearString) {
long monthDate;
List<String> weekEnds = new ArrayList<>();
SimpleDateFormat simpleDateFormat= new SimpleDateFormat("dd,MM,yyyy");
try {
monthYearString="01,".concat(monthYearString);
monthDate = simpleDateFormat.parse(monthYearString).getTime();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(monthDate);
int maxDate = calendar.getActualMaximum(Calendar.DATE);
int minDate = calendar.getActualMinimum(Calendar.DATE);
for (int i = minDate; i <= maxDate; i++) {
calendar.set(Calendar.DATE, i);
if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY|| calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
weekEnds.add(convertToDate(calendar.getTimeInMillis()));
}
}
}catch (Exception e){
e.printStackTrace();
}
return weekEnds;
}
String convertToDate(Long datetime) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMM. yyyy");
Date date = new Date(datetime);
return simpleDateFormat.format(date);
}
you can do it from this method.

How to itrate the json list?

I have a list,that list i have put inside the json object that list I want to iterate using jquery and I need to append to the table.Could anyone please help me to solve this.
This is my action class.
String startdate = request.getParameter("startdate");
String endate = request.getParameter("endate");
String leavepolicyid = request.getParameter("leavepolicyid");
Session session = HibernateUtil.getSessionFactory().openSession();
LeavePolicyEntity lpe = (LeavePolicyEntity) session.get(LeavePolicyEntity.class, Integer.parseInt(leavepolicyid));
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Calendar fromcal = Calendar.getInstance();
fromcal.setTime(sdf.parse(startdate));
Calendar endCal = Calendar.getInstance();
endCal.setTime(sdf.parse(endate));
int actualDays = 0;
boolean excludeWeekends = lpe.isExcludeweekends();
int totalDays = 0;
List daysList = new ArrayList();
StringBuffer sb = new StringBuffer();
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE", Locale.US);
SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MMM-yyyy");
while (!fromcal.after(endCal)) {
sb.setLength(0);
System.out.println("fromcal.get(Calendar.DAY_OF_WEEK)" + fromcal.get(Calendar.DAY_OF_WEEK));
if (excludeWeekends) {
if ((7 != fromcal.get(Calendar.DAY_OF_WEEK)) && (1 != fromcal.get(Calendar.DAY_OF_WEEK))) {
actualDays++;
// String asWeek = dateFormat.format(fromcal.getTime());
sb.append(dateFormat.format(fromcal.getTime()) + "-" + sdf1.format(fromcal.getTime()) + ",true");
} else {
sb.append(dateFormat.format(fromcal.getTime()) + "-" + sdf1.format(fromcal.getTime()) + ",false");
}
} else {
sb.append(dateFormat.format(fromcal.getTime()) + "-" + sdf1.format(fromcal.getTime()) + ",true");
actualDays++;
}
daysList.add(sb.toString());
fromcal.add(Calendar.DATE, 1);
totalDays++;
}
// System.out.println("daysListdaysListdaysList" + daysList);
// JSONObject json = new JSONObject();
// json.accumulate("weekdays", daysList);
response.setContentType("application/json");
String json = new Gson().toJson(daysList);
System.out.println("Json" + json);
response.getWriter().print(json);
Jquery ajax
$("[id^='leavetype']").change(function() {
var startdate = $('#leavetypefromdate').val();
var enddate = $('#leavetypetodate').val();
// alert(startdate)
// alert(enddate)
if (startdate != "" && enddate != "") {
if (new Date(startdate) <= new Date(enddate)) {
$.get("leaverequestvalidation.do?method=validateleavetype", {startdate: startdate, endate: enddate, leavepolicyid: $('#leaveTypeid').val()}, function(responce) {
alert(responce);
$.each(JSON.parse(responce), function(idx, obj) {
alert(1);
});
});
} else {
alert("FromDate Cannot Be Greater Than ToDate")
}
}
});

Android week View how can we Get all days of a next and previous week

I'm able to get current week dates, But How to list previous / next week days ?
This is the method
public String [] getWeekDay()
{
Calendar now = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("dd");
String [] days = new String[7];
int delta = -now.get(GregorianCalendar.DAY_OF_WEEK) + 1;
now.add(Calendar.DAY_OF_MONTH , delta);
for (int i = 0; i < 7; i++)
{
days [i] = format.format(now.getTime());
now.add(Calendar.DAY_OF_MONTH , 1);
}
// System.out.println(Arrays.toString(days));
return days;
}
pls see the image, and tell me how to get the next and previous week days
finally i got the answer pls see this
Get the present Week:
public String [] getWeekDay()
{
Calendar now = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String [] days = new String[7];
int delta = -now.get(GregorianCalendar.DAY_OF_WEEK) + 1;
now.add(Calendar.DAY_OF_MONTH , delta);
for (int i = 0; i < 7; i++)
{
days [i] = format.format(now.getTime());
now.add(Calendar.DAY_OF_MONTH , 1);
}
return days;
}
Get the Next Week:
int weekDaysCount=0;
public String [] getWeekDayNext()
{
weekDaysCount++;
Calendar now1 = Calendar.getInstance();
Calendar now = (Calendar) now1.clone();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String [] days = new String[7];
int delta = -now.get(GregorianCalendar.DAY_OF_WEEK) + 1;
now.add(Calendar.WEEK_OF_YEAR , weekDaysCount);
now.add(Calendar.DAY_OF_MONTH , delta);
for (int i = 0; i < 7; i++)
{
days [i] = format.format(now.getTime());
now.add(Calendar.DAY_OF_MONTH , 1);
}
return days;
}
Get the previous Week:
public String [] getWeekDayPrev()
{
weekDaysCount--;
Calendar now1 = Calendar.getInstance();
Calendar now = (Calendar) now1.clone();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String [] days = new String[7];
int delta = -now.get(GregorianCalendar.DAY_OF_WEEK) + 1;
now.add(Calendar.WEEK_OF_YEAR , weekDaysCount);
now.add(Calendar.DAY_OF_MONTH , delta);
for (int i = 0; i < 7; i++)
{
days [i] = format.format(now.getTime());
now.add(Calendar.DAY_OF_MONTH , 1);
}
return days;
}
to assign the textView
NextPreWeekday = getWeekDay();
firstDayOfWeek = CommonMethod.convertWeekDays(NextPreWeekday [0]);
lastDayOfWeek = CommonMethod.convertWeekDays(NextPreWeekday [6]);
textViewDate.setText(firstDayOfWeek + "-" + lastDayOfWeek + " " + CommonMethod.convertWeekDaysMouth(NextPreWeekday [6]));
textViewSun.setText(CommonMethod.convertWeekDays(NextPreWeekday [0]) + "\nSun");
textViewMon.setText(CommonMethod.convertWeekDays(NextPreWeekday [1]) + "\nMon");
textViewTue.setText(CommonMethod.convertWeekDays(NextPreWeekday [2]) + "\nTue");
textViewWed.setText(CommonMethod.convertWeekDays(NextPreWeekday [3]) + "\nWeb");
textViewThu.setText(CommonMethod.convertWeekDays(NextPreWeekday [4]) + "\nThu");
textViewFri.setText(CommonMethod.convertWeekDays(NextPreWeekday [5]) + "\nFri");
textViewSat.setText(CommonMethod.convertWeekDays(NextPreWeekday [6]) + "\nSat");
public static String convertWeekDays(String date)
{
String formattedDate = null;
try
{
SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd" , Locale.ENGLISH);
SimpleDateFormat targetFormat = new SimpleDateFormat("dd");
Date date12 = originalFormat.parse(date);
formattedDate = targetFormat.format(date12);
} catch (Exception e)
{
e.printStackTrace();
}
return formattedDate;
}
public static String convertWeekDaysMouth(String date)
{
String formattedDate = null;
try
{
SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd" , Locale.ENGLISH);
SimpleDateFormat targetFormat = new SimpleDateFormat("MMM yyyy");
Date date12 = originalFormat.parse(date);
formattedDate = targetFormat.format(date12);
} catch (Exception e)
{
e.printStackTrace();
}
return formattedDate;
}
For current week.
SimpleDateFormat displayDate = new SimpleDateFormat("dd-MMM-yyyyy"));
final Calendar calenderThisWeek = Calendar.getInstance();
calenderThisWeek.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
String strWek = displayDate.format(calenderThisWeek.getTime()); // dd-mmm-yyyy
calenderThisWeek.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
String endWek = displayDate.format(calenderThisWeek.getTime()); // dd-mmm-yyyy
For Previous Week
final Calendar calenderpreviousWeek = Calendar.getInstance();
calenderpreviousWeek.add(Calendar.DAY_OF_WEEK, -1);
calenderpreviousWeek.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
String strWek = displayDate.format(calenderThisWeek.getTime()); // dd-mmm-yyyy
calenderpreviousWeek.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
String endWek = displayDate.format(calenderpreviousWeek.getTime()); // dd-mmm-yyyy
For Next Week
final Calendar calenderNextWeek = Calendar.getInstance();
calenderNextWeek.add(Calendar.DAY_OF_WEEK, +1);
calenderNextWeek.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
String strWek = displayDate.format(calenderNextWeek.getTime()); // dd-mmm-yyyy
calenderNextWeek.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
String endWek = displayDate.format(calenderNextWeek.getTime()); // dd-mmm-yyyy

Categories

Resources