Next day check by using calendar JSF primefaces - date

i am working on a requirement. what i need to do is to retreieve the last enetered date from database, increment it and then check if the day is saturday or not.
the part i am stuck at is how to check if the next day is saturday i am using primefaces 3.5 jsf2.1 apache tomcat 7.0.39
FacesContext context = FacesContext.getCurrentInstance();
Map requestMap = context.getExternalContext().getRequestParameterMap();
String value = (String) requestMap.get("id");
Integer id = Integer.parseInt(value);
SimpleDateFormat sdf= new SimpleDateFormat();
String sector=new String();
setFund(new Fund());
for(Map row:fund_grid){
Integer edit_id=(Integer.parseInt((String) row.get("fund_id")));
if(id.equals(edit_id)){
sector=(String) row.get("fund_sector_label");
mfp.setFund_id(Integer.parseInt( (String) row.get("fund_id")));
fund.setFund_id( (String) row.get("fund_id"));
setValidity_date(request_invoker.select_validity_date());
try {
Date ndate=sdf.parse((String) getValidity_date().get(0).get("validitydate"));
// Date is here retireved from database value 15-11-2013
//now incrementing for a day
Calendar c = Calendar.getInstance();
c.setTime(ndate);
c.add(Calendar.DATE, 1);
fund.setNav_entry_date(c.getTime());
//here is where i am stuck i dont know how to check whether date is of saturday or not
if(fund.getNav_entry_date().equals(Calendar.SATURDAY))
{
c.add(Calendar.DATE, 2);
fund.setNav_entry_date(c.getTime());
}
else
{
fund.setNav_entry_date(c.getTime());
}
} catch (ParseException e) {
e.printStackTrace();
}
}
}
RequestContext context2 = RequestContext.getCurrentInstance();
if(sector.equals("open-end")){
context2.execute("opendialog.show();");
}
else if(sector.equals("close-end")){
context2.execute("closedialog.show();");
}
else if(sector.equals("pension")){
context2.execute("pensiondialog.show();");
}
}
any help much appreciated

Made changes to the bean and it works calendar c has the date from database and d has the curret date.
Calendar c = Calendar.getInstance();
c.setTime(ndate);
Calendar d=Calendar.getInstance();
if(d.get(Calendar.DATE)==(c.get(Calendar.DATE)))
{
//message here
FacesMessage msg = new FacesMessage("NAV Upto Date" , "NAV Upto Date");
FacesContext.getCurrentInstance().addMessage(null, msg);
break;
}
else
{
c.add(Calendar.DATE, 1);
int day=c.SATURDAY;
int week=c.get(Calendar.DAY_OF_WEEK);
if(day==(week))
{
c.add(Calendar.DATE, 2);
fund.setNav_entry_date(c.getTime());
mfp.getDc().setValiditydate(c.getTime());
}
else
{
fund.setNav_entry_date(c.getTime());
mfp.getDc().setValiditydate(c.getTime());
}
RequestContext context2 = RequestContext.getCurrentInstance();
if(sector.equals("open-end")){
context2.execute("openenddialog.show();");
}
else if(sector.equals("close-end")){
context2.execute("closeenddialog.show();");
}
else if(sector.equals("pension")){
context2.execute("pensiondialog.show();");
}
}

Related

Alarm is not triggering when app is killed

I am facing a issue while adding a alarmManager.
Basicly I'm trying to add a alarm on specific time and it's working fine whether app is in background or in foreground. but the issue is that it's not going to trigger when app is removed from background or app is killed.
I want to trigger alarm whether app is running or not (issue faced when app is closed).
I'm little bit desperate.
Here is my Code :
public class AlarmReciver extends BroadcastReceiver {
public AlarmReciver(){
super();
}
#Override
public void onReceive(Context context, Intent intent) {
Log.d("called","called");
Toast.makeText(context, "Alarm received!", Toast.LENGTH_LONG).show();
//This will send a notification message and show notification in notification tray
/* ComponentName comp = new ComponentName(context.getPackageName(),
AlarmNotificationService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));*/
try {
ManageDatabase manageDatabase = new ManageDatabase();
// manageDatabase.setupdatabase(context);
// For our recurring task, we'll just display a message
// Toast.makeText(context, "Alarm received!", Toast.LENGTH_LONG).show();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
String today_date=String.valueOf(calendar.get(Calendar.DAY_OF_MONTH))+"/"+String.valueOf((calendar.get(Calendar.MONTH)+1))+"/"+String.valueOf(calendar.get(Calendar.YEAR));
today_date= datetimeformat.getdate(today_date);
String id = intent.getStringExtra("id").toString();
String pid = intent.getStringExtra("pid").toString();
manageDatabase.cancelallreminders_without_update(context);
manageDatabase.setallactivatedalarm(context);
manageDatabase.addtodaysidlist(id,today_date,context);
// Enable a receiver
/* ComponentName receiver = new ComponentName(context, AlarmReciver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);*/
Intent service1 = new Intent(context, Show_Reminder.class);
service1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
service1.putExtra("id", id);
service1.putExtra("pid", pid);
context.startActivity(service1);
Toast.makeText(context,"alarm is triggered...", Toast.LENGTH_LONG).show();
Log.d("alarm is","triggered");
}catch (Exception e)
{
Log.e("error",e.toString());
e.printStackTrace();
}
}
}
Manifest file :
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name="com.pragma.healthopediaplus.Medicine_reminder.Utils.Reminders.AlarmReciver"
android:exported="false"
android:process=":remote">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.PACKAGE_RESTARTED" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
</intent-filter>
</receiver>
set alarm from database.java
public void setallactivatedalarm(Context context) {
db= context.openOrCreateDatabase("Reminder"+ SharedPreference.getvalue("username",context)+".db",Context.MODE_PRIVATE,null);
Cursor c1 = db.rawQuery("select * from reminderdata",null);
Log.d("Set all activate alarm","inside");
while (c1.moveToNext())
{
if(c1.getString(6).equals("active"))
{
Date date_type=new Date();
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
try {
Gson gson = new Gson();
ArrayList<Info> infodata = gson.fromJson(c1.getString(2), new TypeToken<ArrayList<Info>>() {
}.getType());
// Log.d("reminder", " setReminder " + c1.getString(1) + " " + c1.getString(3) + " " + c1.getString(5) + " " + infodata + " " + Integer.parseInt(c1.getString(4)) + " " + context + " " + Integer.parseInt(c1.getString(0)));
String alltime[]=infodata.get(7).getValue().split(",");
String maxtime= datetimeformat.gettimehhmm(alltime[0]);
String weekday;
for(int i=1;i<alltime.length;i++)
{
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date inTime = sdf.parse(maxtime);
Date outTime = sdf.parse(datetimeformat.gettimehhmm(alltime[i]));
if(outTime.compareTo(inTime) > 0){
maxtime= datetimeformat.gettimehhmm(alltime[i]);
}
}
String timedata=maxtime;
String timearray[]=timedata.split(":");
date_type = format.parse(c1.getString(3));
Calendar newtime = Calendar.getInstance();
newtime.setTime(date_type);
newtime.set(Calendar.MINUTE,Integer.parseInt(timearray[1]));
newtime.set(Calendar.SECOND,00);
newtime.set(Calendar.HOUR_OF_DAY,Integer.parseInt(timearray[0]));
Calendar currenttime=Calendar.getInstance();
if(newtime.getTimeInMillis()<=currenttime.getTimeInMillis())
{
/* flag 1 for everyday 2 for month 3 for everyyear 4 onetime*/
if(c1.getString(4).equals("1"))
{
newtime.add(Calendar.DATE, 1);
}
else if(c1.getString(4).equals("2"))
{
newtime.add(Calendar.MONTH, 1);
}
else if(c1.getString(4).equals("3"))
{
newtime.add(Calendar.YEAR, 1);
}
else if(c1.getString(4).equals("5"))
{
int weekdayint = 0;
int dayOfWeek=newtime.get(Calendar.DAY_OF_WEEK);
String weekDay = null;
if (Calendar.MONDAY == dayOfWeek) {
weekdayint=Calendar.MONDAY;
weekDay = context.getString(R.string.Monday);
} else if (Calendar.TUESDAY == dayOfWeek) {
weekdayint=Calendar.TUESDAY;
weekDay = context.getString(R.string.Tuesday);
} else if (Calendar.WEDNESDAY == dayOfWeek) {
weekdayint=Calendar.WEDNESDAY;
weekDay = context.getString(R.string.Wednesday);
} else if (Calendar.THURSDAY == dayOfWeek) {
weekdayint=Calendar.THURSDAY;
weekDay = context.getString(R.string.Thursday);
} else if (Calendar.FRIDAY == dayOfWeek) {
weekdayint=Calendar.FRIDAY;
weekDay = context.getString(R.string.Friday);
} else if (Calendar.SATURDAY == dayOfWeek) {
weekdayint=Calendar.SATURDAY;
weekDay = context.getString(R.string.Saturday);
} else if (Calendar.SUNDAY == dayOfWeek) {
weekdayint=Calendar.SUNDAY;
weekDay = context.getString(R.string.Sunday);
}
weekday=infodata.get(9).getValue();
String day[]=weekday.split(",");
String next="";
int nxtday = 0;
int addday;
int count[]={1,2,3,4,5,6,7,1,2,3,4,5,6,7};
String getweek[]={"",context.getString(R.string.Sunday),context.getString(R.string.Monday),context.getString(R.string.Tuesday)
,context.getString(R.string.Wednesday), context.getString(R.string.Thursday),
context.getString(R.string.Friday),context.getString(R.string.Saturday)};
for(int i=weekdayint;i<weekdayint+7;i++)
{
int c=count[i];
if (Arrays.asList(day).contains(getweek[c])) {
next=getweek[c];
nxtday=c;
break;
}
}
if(nxtday>weekdayint)
{
addday=nxtday-weekdayint;
}else
{
addday=nxtday-weekdayint+7;
}
newtime.add(Calendar.DATE, addday);
}
int thisYear = newtime.get(Calendar.YEAR);
int thisMonth = newtime.get(Calendar.MONTH);
int thisDay = newtime.get(Calendar.DAY_OF_MONTH);
String newdate=thisDay+"/"+(thisMonth+1)+"/"+thisYear;
newdate=datetimeformat.getdate(newdate);
db.execSQL("update reminderdata set duedate='"+newdate+"'where id='"+c1.getString(0)+"'");
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("error",e.toString());
}
Gson gson = new Gson();
ArrayList<Info> infodata = gson.fromJson(c1.getString(2), new TypeToken<ArrayList<Info>>() {
}.getType());
// Log.d("reminder", " setReminder "+c1.getString(1)+" "+c1.getString(3)+" "+ c1.getString(5)+" "+ infodata+" "+Integer.parseInt(c1.getString(4))+" "+ context+" "+Integer.parseInt(c1.getString(0)));
String alltime[]=infodata.get(7).getValue().split(",");
Log.d("all time",infodata.get(7).getValue());
Log.d("all time length",alltime.length+"");
String pid[]=getPidsfromrid(Integer.parseInt(c1.getString(0)),context).split(",");
for(int i=0;i<alltime.length;i++)
{Log.d("pids",pid[i]);
Log.d("set reminder called",alltime[i]);
setReminder( c1.getString(3), context,
Integer.parseInt(c1.getString(0)),alltime[i],Integer.parseInt(pid[i]));
}
}
}
db.close();
}
public boolean setReminder(String date,Context context,int id,String time,int pid) {
Intent myIntent = new Intent(context, AlarmReciver.class);
myIntent.putExtra("id",String.valueOf(id));
myIntent.putExtra("pid",String.valueOf(pid));
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, myIntent,
0);
Date date_type=new Date();
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
try
{
date_type = format.parse(date);
} catch (Exception e) {
e.printStackTrace();
}
String timedata= datetimeformat.gettimehhmm(time);
String timearray[]=timedata.split(":");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date_type);
calendar.set(Calendar.MINUTE,Integer.parseInt(timearray[1]));
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.HOUR_OF_DAY,Integer.parseInt(timearray[0]));
Calendar current = Calendar.getInstance();
Log.d("set reminder inside",time);
if(calendar.compareTo(current) <= 0){
calendar.add(Calendar.DATE, 1);
Log.d("set reminder inside ","not set alarm"+time);
// Toast.makeText(context,"Invalid Date/Time",Toast.LENGTH_LONG).show();
} else{
Log.d("set reminder inside ","set alarm"+time);
Log.d("set reminder inside",time);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(),
pendingIntent);
/* int SDK_INT = Build.VERSION.SDK_INT;
if (SDK_INT < Build.VERSION_CODES.KITKAT)
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
else if (Build.VERSION_CODES.KITKAT <= SDK_INT && SDK_INT < Build.VERSION_CODES.M)
alarmManager.setExact(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), pendingIntent);
else if (SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), pendingIntent);
}
*/
/*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis()+2000, pendingIntent);
}else {
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis()+2000, pendingIntent);
}*/
}
try {
//Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
Closing the app closes all the Alarms as well. What you need instead is to set up Alarms from a Background Service instead.
You can reuse almost all of your existing code, and will have to create an additional class (preferably in new file) for the service. You'll also have to register the service in the manifest file, and move the code for creating alarm into the service class.
Example for creating a background service is here: https://developer.android.com/training/run-background-service/create-service
Note the background services have some limitations, but they can be set to be active even after REBOOT of the device.
Depending on your use case, you could also look into JobScheduler, that can run periodically and use that to set Alarms (dynamically, or otherwise). If your Alarms don't have to be 'Exact', you can just get the task done in JobScheduler itself, as it's almost as accurate as Alarm Manager. I say this because after Android O, doze mode takes away accuracy of Alarm Manager as well as JobScheduler.

How to handle datepicker in Katalon studio?

How to handle datepicker control in Katalon studio?
I am very new to Katalon studio.
Here is custom keyword to handle bootstrap date-picker.
package framework
class component{
#Keyword
public static void handleDatepicker(TestObject calender, String exp_Date, String exp_Month,
String exp_Year) throws Exception {
String expDate = null, calYear = null,datepickerText=null,minYear=null,maxYear=null;
int expMonth = 0, expYear = 0;
WebElement datePicker;
List<WebElement> noOfDays=null,noOfMonths=null,noOfYears=null;
boolean dateNotFound = true;
List<String> monthList = Arrays.asList("None","Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
"Aug", "Sep", "Oct", "Nov", "Dec");
def driver = DriverFactory.getWebDriver()
WebElement SelectCalender = WebUiCommonHelper.findWebElement(calender, 20);
SelectCalender.click()
expDate = (exp_Date);
expMonth = Integer.parseInt(exp_Month);
expYear = Integer.parseInt(exp_Year);
WebElement datePicker_Heading1 =(driver).findElement(By.xpath("//div[#class='datepicker-days']/table/thead/tr[1]/th[2]"));
WebDriverWait wait = new WebDriverWait(driver,10);
wait.until(ExpectedConditions.elementToBeClickable(datePicker_Heading1));
datePicker_Heading1.click();
WebElement datePicker_Heading2 =(driver).findElement(By.xpath("//div[#class='datepicker-months']/table/thead/tr[1]/th[2]"));
wait.until(ExpectedConditions.elementToBeClickable(datePicker_Heading2));
datePicker_Heading2.click();
while (dateNotFound) {
WebElement datePicker_Heading3 =(driver).findElement(By.xpath("//div[#class='datepicker-years']/table/thead/tr[1]/th[2]"));
wait.until(ExpectedConditions.visibilityOf(datePicker_Heading3));
datepickerText =datePicker_Heading3.getText();
String[] datepickerYear = datepickerText.split("-");
minYear =datepickerYear[0];
maxYear = datepickerYear[1];
if((expYear >= Integer.parseInt(minYear)) && (expYear<=Integer.parseInt(maxYear)))
{
datePicker = (driver).findElement(By.xpath("//div[#class='datepicker-years']/table"));
noOfYears = datePicker.findElements(By.xpath("//span[contains(#class,'year')]"));
firstloop:
for (WebElement year : noOfYears) {
if (year.getText().equalsIgnoreCase((String)exp_Year)) {
year.click();
Thread.sleep(1500);
datePicker = (driver).findElement(By.xpath("//div[#class='datepicker-months']/table"));
//noOfMonths = datePicker.findElements(By.xpath("//span[#class='month']"));
noOfMonths = datePicker.findElements(By.cssSelector("span.month"));
Thread.sleep(1000);
for (WebElement month : noOfMonths) {
System.out.println(" the expected month in int is : "+expMonth);
System.out.println(" the expected month is : "+monthList.get(expMonth));
System.out.println(" the Actual month is : "+month.getText());
if ((monthList.get(expMonth)).equalsIgnoreCase(month.getText())) {
System.out.println("days ");
month.click();
datePicker = (driver).findElement(By.xpath("//div[#class='datepicker-days']/table"));
noOfDays = datePicker.findElements(By.xpath("//td[#class='day']"));
Thread.sleep(1500);
for (WebElement cell : noOfDays) {
if (cell.getText().equalsIgnoreCase(expDate)) {
System.out.println("days ");
cell.click();
break firstloop;
}
}
}
}
}
}
dateNotFound = false;
}else if (expYear > Integer.parseInt(maxYear)) {
WebElement Next =(driver).findElement(By.xpath("//div[#class='datepicker-years']/table/thead/tr[1]/th[#class='next']"));
if(Next.getAttribute("style").equalsIgnoreCase("visibility: visible;"))
{// Click on next button of date picker.
Next.click();
}else {
throw new Exception("This is exception")
}
}
// If current selected month and year are greater than expected
// month and year then go Inside this condition.
else if (expYear < Integer.parseInt(minYear)) {
WebElement Previous =(driver).findElement(By.xpath("//div[#class='datepicker-years']/table/thead/tr[1]/th[#class='prev']"));
if(Previous.getAttribute("style").equalsIgnoreCase("visibility: visible;"))
{
// Click on previous button of date picker.
Previous.click();
}else{
throw new Exception("This is exception")
}
}
}
}
}
You can use above keyword as below
CustomKeywords.'framework.component.handleDatepicker'(findTestObject('testobject'),'10', '12', '1990')
Note : "Framework" folder had been created by us as inside the Keyword folder and then We had created the "component" keyword
This way you can able to create custom keyword as per your component.
I hope this might help you and other developers.
Maybe this can help, it seems to be a similar situation:
https://forum.katalon.com/discussion/1999/how-to-handle-date-pickers-in-katalon.
There are some generic project templates in Katalon Studio 6.2.0. One of them is "Tips and Tricks with Katalon Studio" that contains a "Datepicker.groovy" file with this generic datepicker code that you can adapt as you wish:
import static com.kms.katalon.core.testobject.ObjectRepository.findTestObject
import com.kms.katalon.core.annotation.Keyword
import com.kms.katalon.core.model.FailureHandling
import com.kms.katalon.core.testobject.TestObject
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI
import static java.util.Calendar.*
import org.apache.xerces.jaxp.datatype.XMLGregorianCalendarImpl.DaysInMonth
class Datepicker {
Date date;
TestObject obj;
Datepicker() {}
Datepicker(TestObject object, String input_date) {
this.obj = object;
date = new Date().parse("MM/dd/yyyy", input_date)
}
def open_calendar_form() {
WebUI.waitForElementClickable(this.obj, 0)
WebUI.click(this.obj)
}
def displaying_month() {
WebUI.waitForElementVisible(findTestObject('Object Repository/jqueryui/widgets/datepicker/date_month'), 0)
return WebUI.getText(
findTestObject('Object Repository/jqueryui/widgets/datepicker/date_month'),
FailureHandling.STOP_ON_FAILURE)
}
def displaying_year() {
WebUI.waitForElementVisible(findTestObject('Object Repository/jqueryui/widgets/datepicker/date_year'), 0)
return WebUI.getText(
findTestObject('Object Repository/jqueryui/widgets/datepicker/date_year'),
FailureHandling.STOP_ON_FAILURE)
}
def displaying_date() {
return new Date().parse("MMM/yyyy", displaying_month() + "/" + displaying_year())
}
def pick_year() {
if (displaying_date()[YEAR] == date[YEAR]) return
while (displaying_date()[YEAR] < date[YEAR]) {
WebUI.click(findTestObject('Object Repository/jqueryui/widgets/datepicker/Next'))
}
while (displaying_date()[YEAR] > date[YEAR]) {
WebUI.click(findTestObject('Object Repository/jqueryui/widgets/datepicker/Prev'))
}
}
def pick_month() {
if (displaying_date()[MONTH] == date[MONTH]) return
while (displaying_date()[MONTH] < date[MONTH]) {
WebUI.click(findTestObject('Object Repository/jqueryui/widgets/datepicker/Next'))
}
while (displaying_date()[MONTH] > date[MONTH]) {
WebUI.click(findTestObject('Object Repository/jqueryui/widgets/datepicker/Prev'))
}
}
def pick_day() {
println date[DAY_OF_MONTH]
WebUI.click(findTestObject('Object Repository/jqueryui/widgets/datepicker/date_day', [('day') : date[DAY_OF_MONTH]]))
}
def pick_date() {
pick_year()
pick_month()
pick_day()
}
#Keyword
def pickDate(TestObject ob, String date) {
def picker = new Datepicker(ob, date)
picker.open_calendar_form()
picker.pick_date()
}
}
If your datepicker widget is anything like the ones in Zoho (it auto-populates with today's date, and setting the text to different date either has no effect or appends to today's date string), try this out:
public final class GeneralWebUIUtils {
public static final String VALUE = "value";
public static String GetTextValue(TestObject to) {
return WebUI.getAttribute(to, this.VALUE)
}
public static Keys GetCommandKey() {
final String os = System.getProperty("os.name")
if (os.toUpperCase().contains("WINDOWS"))
return Keys.CONTROL;
return Keys.COMMAND;
}
public static void ClearAndEnterText(TestObject to, String text) {
WebUI.sendKeys(to,
Keys.chord("${this.GetCommandKey().toString()}A"),
FailureHandling.STOP_ON_FAILURE);
WebUI.sendKeys(to, text, FailureHandling.STOP_ON_FAILURE);
}
public static void UpdateDateField(TestObject to, Date newDate) {
this.WaitForTextFieldNonEmpty(to, 1, FailureHandling.CONTINUE_ON_FAILURE)
if (newDate == null) {
WebUI.clearText(to, FailureHandling.STOP_ON_FAILURE);
return;
}
final String fieldTextValue = this.GetTextValue(to),
newDateTextValue = SMDDateUtils.ToDateString(newDate);
if ((!newDateTextValue.isEmpty()) && (!fieldTextValue.equals(newDateTextValue))) {
this.ClearAndEnterText(to, newDateTextValue);
KeywordUtil.logInfo("'${newDateTextValue}' written to the date field")
}
WebUI.sendKeys(to, Keys.TAB.toString());
KeywordUtil.logInfo("After trying to write to the field, it has value '${this.GetTextValue(to)}'")
}
public static boolean WaitForElementCondition(Closure<Boolean> onCheckCondition, Closure onContinue, TestObject to, int timeOut, FailureHandling failureHandling = FailureHandling.STOP_ON_FAILURE) {
final long startTime = System.currentTimeMillis()
boolean isConditionSatisfied = false;
while ((System.currentTimeMillis() < startTime + timeOut * 1000) && (!isConditionSatisfied)) {
isConditionSatisfied = WebUI.waitForElementPresent(to, 1, failureHandling) && onCheckCondition(to);
if (onContinue != null)
onContinue(isConditionSatisfied, to);
}
if ((!isConditionSatisfied) && (failureHandling.equals(FailureHandling.STOP_ON_FAILURE))) {
KeywordUtil.markFailedAndStop("Condition for TestObject '${to.getObjectId()}' not met after ${(System.currentTimeMillis() - startTime) / 1000} seconds");
}
return isConditionSatisfied;
}
public static boolean WaitForTextFieldNonEmpty(TestObject to, int timeOut, FailureHandling failureHandling = FailureHandling.STOP_ON_FAILURE) {
return this.WaitForElementCondition({ TestObject testObj ->
return (!this.GetTextValue(testObj).isEmpty());
},
null,
to,
timeOut,
failureHandling);
}
}
public final class SMDDateUtils {
// TODO: replace with the date format that you use in your project
private static DateFormat DateFormat = new SimpleDateFormat("MM-dd-yyyy");
public static String ToDateString(Date date) {
return this.DateFormat.format(date);
}
}
Save that to two keywords: GeneralWebUIUtils and SMDDateUtils (feel free to replace the name prefix on that one :) )
Then you can just be like:
GeneralWebUIUtils.UpdateDateField(findTestObject('Order/dataSigned'), todaysDate)
to update to todaysDate
and even
GeneralWebUIUtils.UpdateDateField(findTestObject('Order/dataSigned'), null)
to clear it! :)
DISCLAIMER: those utils are pulled straight from my testing codebase.

Retrive Data using by $or and $and from two MongoDB collectionDa

What i am trying to do is display the response from a POST message on to the HTML loaded in my webview. However, the my webview appears blank. I can see the response message by in LogCat by printing it out. However, again my webview appears blank. Example.html is the page loading in my webview. My implementation is below:
private void startSchedule()
{
for(int i=0;i<temPojoData.size();i++)
{
tempPojo tem =temPojoData.get(i);
/////////////////////// Daily and AllDays functionality start here //////////////////
if(tem.getDaysweekmonth().equals("Daily") )
{
if(tem.getDaysbases().equals("AllDays")) {
if (findDateBTwoDates(tem.getStartDate(), tem.getEndDate())) {
Log.i("Daily Date", "Today Available");
layoutID += tem.getLayout();
}
}else if(tem.getDaysbases().equals("Whole Day")){
}else if(tem.getDaysbases().equals("Morning"))
{ scheduleStartTimes.add(tem.getStartTime());
}else if(tem.getDaysbases().equals("After Noon"))
{ scheduleStartTimes.add(tem.getStartTime());
}else if(tem.getDaysbases().equals("Evening"))
{ scheduleStartTimes.add(tem.getStartTime());
}else if(tem.getDaysbases().equals("Night"))
{ scheduleStartTimes.add(tem.getStartTime());
}else if(tem.getDaysbases().equals("Choose Time"))
{ scheduleStartTimes.add(tem.getStartTime());
}
}
/////////////////////// Weekly and AllDays functionality start here //////////////////
else if(tem.getDaysweekmonth().equals("weekly") && tem.getDaysbases().equals("AllDays"))
{
if(tem.getDaysbases().equals("AllDays")) {
}
}
/////////////////////// Monthly and AllDays functionality start here //////////////////
else if(tem.getDaysweekmonth().equals("montly") && tem.getDaysbases().equals("AllDays"))
{
if(tem.getDaysbases().equals("AllDays")) {
}
}
}
}
private void findTimeBTwoTimes(String sTime,String eTime)
{
try {
String string1 = "20:11:13";
Date time1 = new SimpleDateFormat("HH:mm:ss").parse(string1);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
String string2 = "14:49:00";
Date time2 = new SimpleDateFormat("HH:mm:ss").parse(string2);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time2);
calendar2.add(Calendar.DATE, 1);
String someRandomTime = "01:00:00";
Date d = new SimpleDateFormat("HH:mm:ss").parse(someRandomTime);
Calendar calendar3 = Calendar.getInstance();
calendar3.setTime(d);
calendar3.add(Calendar.DATE, 1);
Date x = calendar3.getTime();
if (x.after(calendar1.getTime()) && x.before(calendar2.getTime())) {
//checkes whether the current time is between 14:49:00 and 20:11:13.
System.out.println(true);
}
} catch (ParseException e) {
e.printStackTrace();
}
}
private boolean findDateBTwoDates(String sDate,String eDate)
{
try {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
String s = sDate.replace(" AM","");
String e = eDate.replace(" AM","");
String oeStartDateStr =sDate.replace("PM","");
String oeEndDateStr =eDate.replace("PM","");
Log.i("Start End Date ",sDate+"------------"+eDate);
Calendar cal = Calendar.getInstance();
Integer year = cal.get(Calendar.YEAR);
Date startDate = sdf.parse(oeStartDateStr);
Date endDate = sdf.parse(oeEndDateStr);
Date d = new Date();
String currDt = sdf.format(d);
if ((d.after(startDate) && (d.before(endDate))) || (currDt.equals(sdf.format(startDate)) || currDt.equals(sdf.format(endDate)))) {
System.out.println("Date is between 1st april to 14th nov...");
return true;
}
/*else {
System.out.println("Date is not between 1st april to 14th nov...");
}*/
}catch (Exception e){}
return false;
}
I will explain this in a sudo code so that you can come up with a solution.
The first point to your answer is that -> No, you cannot do it in a straightforward manner. The reason behind this is that MongoDB does not have/support joins. Like in SQL where you can join two tables and query them for conditional results; the same is not doable in MongoDB.
But do not lose hope. You cannot do a join on the DB side but you can certainly come up with a solution on the driver/application side. What I would suggest you to do is as follows. (I am using the JAVA driver and Morphia so my solutions' arrangement may look specific to them)
Have a DAO interface for both collections seperately
public interface MyDAO1 extends DAO<MyClass1, ObjectId>
{
public MyClass1 getByName(String name);
}
public interface MyDAO2 extends DAO<MyClass2, ObjectId>
{
public MyClass2 getByResult(int result);
}
First make implementation classes for both the above interfaces. That's pretty simple so I am skipping it to move on to the real part. Have an implementation of the interface
public class MyDAOImpl extends BasicDAO<MyClass, ObjectId> implements MyDAO1, MyDAO2
{
public MyClass1 getByName (String name)
{
MyClass1 output= query collection1 with with the Name;
return output;
}
public MyClass2 getByResult (int result)
{
MyClass2 output= query collection2 with with the result;
return output;
}
public void getByNameResult (String name, int result)
{
MyClass1 output1 = getByName (name);
MyClass2 output2 = getByResult (result);
print them in however format you want OR create a string;
}
}
please note:
MyClass1 is the #Entity class for the employee collection
MyClass2 is the #Entity class for the result collection

How I count all the number of records in a RecordStore

I have a LWUIT app that should display the number of records in a LWUIT list.
To get all the records I use a method called getRecordData() that returns all records as a String array, it works fine.
But how do I count the number of these records?
import java.util.*;
import com.sun.lwuit.events.*;
import javax.microedition.midlet.*;
import com.sun.lwuit.*;
import com.sun.lwuit.plaf.*;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms .*;
public class number_of_records extends MIDlet {
private RecordStore recordStore;
// Refresh2( ) method for getting the time now
public String Refresh2()
{
java.util.Calendar calendar = java.util.Calendar.getInstance();
Date myDate = new Date();
calendar.setTime(myDate);
StringBuffer time = new StringBuffer();
time.append(calendar.get(java.util.Calendar.HOUR_OF_DAY)).append(':');
time.append(calendar.get(java.util.Calendar.MINUTE)) ;
// time.append(calendar.get(java.util.Calendar.SECOND));
String tt = time.toString();
return tt;
}
// return all records of recordStore RecordStore
public String [] getRecordData( )
{
String[] str = null;
int counter = 0;
try
{
RecordEnumeration enumeration = recordStore.enumerateRecords(null, null, false);
str = new String[recordStore.getNumRecords()];
while(enumeration.hasNextElement())
{
try
{
str[counter] = (new String(enumeration.nextRecord()));
counter ++;
}
catch(javax.microedition.rms.RecordStoreException e)
{
}
}
}
catch(javax.microedition.rms.RecordStoreNotOpenException e)
{
}
catch(java.lang.NullPointerException n)
{
}
return str;
}
public void startApp()
{
com.sun.lwuit.Display.init(this);
final Button addition = new Button("add a goal");
final com.sun.lwuit.TextField tf = new com.sun.lwuit.TextField();
final com.sun.lwuit.List mylist = new com.sun.lwuit.List();
final Button All = new Button("All Goals");
final com.sun.lwuit.Form ff = new com.sun.lwuit.Form();
final com.sun.lwuit.Form g = new com.sun.lwuit.Form();
ff.getStyle().setBgColor(0X99CCFF);
All.getStyle().setBgColor(0X0066CC);
Style g_style5 = g.getSelectedStyle() ;
g.addComponent(tf);
g.addComponent(addition);
addition.getStyle().setBgColor(0X0066CC);
g.addComponent(All);
g.getStyle().setBgColor(0X99CCFF);
addition.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
//
String s =tf.getText();
if( s!=null && s.length() > 0)
{
try
{
// Store the time in the String k
String k = Refresh2();
// The record and the time stored in KK String
String kk =tf.getText()+"-"+k;
// Add an item (the kk String) to mylist List.
mylist.addItem(kk);
byte bytestream[] = kk.getBytes() ;
// Add a record to recordStore.
int i = recordStore.addRecord(bytestream, 0, bytestream.length);
}
catch(Exception ex) { }
// Inform the User that he added the a record.
Dialog validDialog = new Dialog(" ");
Style Dialogstyle = validDialog.getSelectedStyle() ;
validDialog.setScrollable(false);
validDialog.getDialogStyle().setBgColor(0x0066CC);
validDialog.setTimeout(1000); // set timeout milliseconds
TextArea textArea = new TextArea("...."); //pass the alert text here
textArea.setFocusable(false);
textArea.setText("A goal has been added"+"" );
validDialog.addComponent(textArea);
validDialog.show(0, 10, 10, 10, true);
}
// Information to user that he/she didn’t add a record
else if((s==null || s.length()<= 0))
{
Dialog validDialo = new Dialog(" ");
validDialo.setScrollable(false);
validDialo.getDialogStyle().setBgColor(0x0066CC);
validDialo.setTimeout(5000); // set timeout milliseconds
TextArea textArea = new TextArea("...."); //pass the alert text here
textArea.setFocusable(false);
textArea.setText("please enter scorer name or number");
validDialo.addComponent(textArea);
validDialo.show(50, 50, 50, 50, true);
}
}
});
/*Action here for displaying all records of recordStore RecordStore in a new form */
All.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try
{
recordStore = RecordStore.openRecordStore("My Record Store", true);
}
catch(Exception ex) {}
try
{
com.sun.lwuit.Label l = new com.sun.lwuit.Label(" Team Goals") ;
ff.addComponent(l);
// Store the records of recordStore in string array
String [] record= getRecordData();
int j1;
String valueToBeInserted2="";
int k=getRecordData().length;
for( j1=0;j1< getRecordData().length;j1++)
{
valueToBeInserted2=valueToBeInserted2 + " " + record[j1];
if(j1==getRecordData().length)
{
mylist.addItem(record[j1]);
int m = getRecordData().length;
// Counting the number of records
String goals =""+getRecordData().length;
/* I tried to use for…loop to count them by length of the recordStore and render it.
This list also should display the number of records on the form.
But it didn’t !!!
*/
mylist.addItem(goals);
}
}
ff.addComponent(mylist);
}
catch(java.lang.IllegalArgumentException e)
{
}
finally
{
ff.show();
}
}
}
);
g.show();
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional) {
}
}
I Wrote this code but it gives NullPointerException at recordStore.enumerateRecords (null, null,true);
So I think the problem here.
please help.
myButton.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvet av)
{
try
{
RecordEnumeration enumeration = recordStore.enumerateRecords (null, null,true);
int o =recordStore.getNumRecords () ;
}
catch(Exception e)
{
}
}
});
what you need is enumeration.numRecords(); i reckon recordStore.getNumRecords() should work also, since this is what you are using the populate the array, you could even use the length of the array itself. These options are all in the code, it would be better to explore a bit more and also check the documentation to resolve trivial problems.
you could use the length of the array or set a RecordListener to your recordstore and increase a counter when added a record to recordstore.
here is the solution of my problem , I do a for loop to get the number of
elements of the array.
the counter should be the length of array
count.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent av)
{
try
{
recordStore = RecordStore.openRecordStore("recordStore", true);
}
catch(Exception e)
{ }
try
{
RecordEnumeration enumeration = recordStore.enumerateRecords (null, null,true);
}
catch(Exception e)
{
}
String record[] = getRecordData();
int j;
j = record.length-1;
Dialog validDialog = new Dialog(" ");
Style Dialogstyle = validDialog.getSelectedStyle() ;
validDialog.setScrollable(false);
validDialog.getDialogStyle().setBgColor(0x0066CC);
validDialog.setTimeout(1000); // set timeout milliseconds
TextArea textArea = new TextArea("....");
textArea.setFocusable(false);
textArea.setText("Number Counted"+j );
validDialog.addComponent(textArea);
validDialog.show(0, 10, 10, 10, true);
}});

Want to compare the date with today's date and update the database.

I am trying to compare the userr entered date with today's date and update the database accordingly. This is how i am doing..
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("MM-dd-yyyy");
today = df.format(c.getTime());
//===================================================================
try{
ContentValues val1 = new ContentValues();
val1.put(CPUser.Data.TASK_TYPE, "Todays Task");
getContentResolver().update(CPUser.Data.CONTENT_URI, val1, CPUser.Data.TASK_DUE_DATE + "=" +"'"+today+"'",null);
ContentValues val2 = new ContentValues();
val2.put(CPUser.Data.TASK_TYPE, "Overdue Task");
getContentResolver().update(CPUser.Data.CONTENT_URI, val2, CPUser.Data.TASK_DUE_DATE + "<" +"'"+today+"'",null);
ContentValues val3 = new ContentValues();
val3.put(CPUser.Data.TASK_TYPE, "Active Task");
getContentResolver().update(CPUser.Data.CONTENT_URI, val3, CPUser.Data.TASK_DUE_DATE + ">" +"'"+today+"'",null);
}
Catch(Exception ex)
{ }
If you want to store dates as text in the database, you always have to use "yyyy-MM-dd" format, otherwise you would not be able to do comparisons other than equal ("="). What I do is to save all dates, times and timestamps as INT using Unix Epoch. This allows you to display dates in different formats (using locale for example) to display dates, without first parsing the date. It also allows any type of comparison (equals, greater than etc). The functions are straight forward:
public static long timestampFromUnixEpoch(long unixepoch) {
if (unixepoch == 0)
return 0;
return (unixepoch * 1000) - TimeZone.getDefault().getRawOffset();
}
public static long unixEpochFromTimestamp(long timestampMS) {
if (timestampMS == 0)
return 0;
return ((timestampMS + TimeZone.getDefault().getRawOffset()) / 1000);
}
public static long dateToUnixEpoch(Date date) {
if (date == null)
return 0;
return unixEpochFromTimestamp(date.getTime());
}
public static Date unixEpochToDate(long unixepoch) {
if (unixepoch == 0)
return null;
return new Date(timestampFromUnixEpoch(unixepoch));
}