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

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

Related

How to add employee in ArrayList

Please someone help me how to find the error in the code. I can't add an employee to the arraylist using the switch operator. Тhe code does not show any errors but does not work properly and the array is not filled with anything. Thanks in advance!
class Program
{
class Employee : IComparable
{
private string name;
private int level;
private DateTime hiringDate;
public Employee(string name, int level, DateTime hiringDate)
{
this.name = name;
this.level = level;
this.hiringDate = hiringDate;
}
public string Name
{
get { return name; }
set { this.name = value; }
}
public int Level
{
get { return level; }
set { this.level = value; }
}
public DateTime HiringDate
{
get { return hiringDate; }
set { this.hiringDate = value; }
}
public int CompareTo(object obj)
{
if(obj == null)
{
return 1;
}
Employee other = obj as Employee;
int value = this.level.CompareTo(other.level);
if (value == 0)
{
value = this.hiringDate.CompareTo(other.hiringDate);
}
return value;
}
public void Description()
{
Console.WriteLine("Name: {0}, Level: {1}, Hiring Date: {2}", name, level, hiringDate.ToString());
}
}
static void Main(string[] args)
{
bool exit = false;
ArrayList employees = new ArrayList();
string name;
int level, pos;
Employee mostExp;
DateTime hiringDate;
while (!exit)
{
Console.WriteLine("---------------MENU!---------------");
Console.WriteLine("1. Display employees by level.");
Console.WriteLine("2. Add new employee to list.");
Console.WriteLine("3. Remove employee from list.");
Console.WriteLine("4. Search for employee by name.");
Console.WriteLine("5. Get employee with most work expirience. ");
Console.WriteLine("6. Exit!");
int choice = int.Parse(Console.ReadLine());
switch (choice)
{
case 1:
employees.Sort();
Console.WriteLine("----------------------------------");
foreach (Employee employee in employees)
{
employee.Description();
}
Console.WriteLine("----------------------------------");
break;
case 2:
Console.WriteLine("Enter employee name: ");
name = Console.ReadLine();
Console.WriteLine("Enter employee level: ");
level= int.Parse(Console.ReadLine());
Console.WriteLine("Enter hiring date 'yyyy-mm-dd': ");
hiringDate = DateTime.Parse(Console.ReadLine());
break;
case 3:
Console.WriteLine("Delete employee at position: ");
pos = int.Parse(Console.ReadLine());
employees.RemoveAt(pos);
break;
case 4:
Console.WriteLine("Enter employee name: ");
name = Console.ReadLine();
Console.WriteLine("----------------------------------");
foreach (Employee employee in employees)
{
if (employee.Name == name)
{
employee.Description();
}
}
Console.WriteLine("----------------------------------");
break;
case 5:
mostExp = (Employee)employees[0];
foreach (Employee employee in employees)
{
if(mostExp.HiringDate.CompareTo(employee.HiringDate) == 1)
{
mostExp = employee;
}
}
Console.WriteLine("Employee with most work experience:");
mostExp.Description();
break;
default:
return;
}
}
}
}
In you switch case you are reading certain values from the command line, and you store them in some local variables (name, level, hiringdate) but you aren't making an Employee object at all: Employee emp = Employee(name, level, hiringdate). Then you have to add that employee to the ArrayList: employees.add(emp).

what causes ConstraintMatchTotal could not add constraintMatch, when issue is tied to a .drl 'or' clause?

In extending code from OptaPlanner nurse rostering sample code. What causes the "constraintMatchTotal could not add constraintMatch" (Illegal state?) error to be thrown, that would be related to the parsing of a .drl rule with an 'or' clause, please? It is occurring immediately at import of data into .drl-based ruleset... but does NOT error if either of the two 'or' clauses is commented out. I believe that as they individually are acceptable, the system should handle them in the 'or' setup.
The rule is below, followed by the error, and the domain object used in the 'or' clause. I confirmed that:
If I comment out the 'or' and the BoundaryDate clause above it, the
program loads and runs.
If I comment out the 'or' and the BoundaryDate clause below it, the program loads and runs.
If I leave both in place, the error (below the rule) is thrown immediately.
Additionally, if I insert this clause into the 2nd BoundaryDate condition (after the 'or'), then the program loads and runs:
preferredSequenceStart == true,
.drl rule:
rule "Highlight irregular shifts"
when
EmployeeWorkSameShiftTypeSequence(
employee != null,
$firstDayIndex : firstDayIndex,
$lastDayIndex : lastDayIndex,
$employee : employee,
$dayLength : dayLength)
(
BoundaryDate(
dayIndex == $firstDayIndex,
preferredSequenceStart == false // does not start on a boundary start date
)
or // or
BoundaryDate(
dayIndex == $firstDayIndex,
$dayLength != preferredCoveringLength // is incorrect length for exactly one block
)
)
StaffRosterParametrization($lastDayIndex >= planningWindowStartDayIndex) // ignore if assignment is in (fixed) prior data
// non-functional identification drives desired indictment display on ShiftAssignment planning objects
ShiftAssignment(employee == $employee, shiftDateDayIndex >= $firstDayIndex, shiftDateDayIndex <= $lastDayIndex)
then
scoreHolder.addSoftConstraintMatch(kcontext, -1);
end
Exception executing consequence for rule "Highlight irregular shifts" in westgranite.staffrostering.solver: java.lang.IllegalStateException: The constraintMatchTotal (westgranite.staffrostering.solver/Highlight irregular shifts=0hard/-274soft) could not add constraintMatch (westgranite.staffrostering.solver/Highlight irregular shifts/[2020-01-02/D/6, 2018-12-25 - 2020-01-06, 2020-01-02, ...
[continues on with a list of constraint matches]
The BoundaryData.java is below, so the methods being called from the rule are visible:
package westgranite.staffrostering.domain;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import westgranite.common.domain.AbstractPersistable;
#XStreamAlias("BoundaryDate")
public class BoundaryDate extends AbstractPersistable {
/**
*
*/
private static final long serialVersionUID = -7393276689810490427L;
private static final DateTimeFormatter LABEL_FORMATTER = DateTimeFormatter.ofPattern("E d MMM");
private int dayIndex;
private LocalDate date;
private boolean preferredSequenceStart; // true means "this date is a preferred start to assignment sequences"
private boolean preferredSequenceEnd; // true means "this date is a preferred end for assignment sequences"
private int nextPreferredStartDayIndex; // MAX_VALUE means "none"; if preferredSequenceStart is true, then this ref is still to the FUTURE next pref start date
private int prevPreferredStartDayIndex; // MIN_VALUE means "none"; if preferredSequenceStart is true, then this ref is still to the PREVIOUS next pref start date
// magic value that is beyond reasonable dayIndex range and still allows delta of indices to be an Integer
public static final int noNextPreferredDayIndex = Integer.MAX_VALUE/3;
public static final int noPrevPreferredDayIndex = Integer.MIN_VALUE/3;
public int getDayIndex() {
return dayIndex;
}
public void setDayIndex(int dayIndex) {
this.dayIndex = dayIndex;
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public boolean isPreferredSequenceStart() {
return preferredSequenceStart;
}
public void setPreferredSequenceStart(boolean preferredSequenceStart) {
this.preferredSequenceStart = preferredSequenceStart;
}
public boolean isPreferredSequenceEnd() {
return preferredSequenceEnd;
}
public void setPreferredSequenceEnd(boolean preferredSequenceEnd) {
this.preferredSequenceEnd = preferredSequenceEnd;
}
public int getNextPreferredStartDayIndex() {
return nextPreferredStartDayIndex;
}
public void setNextPreferredStartDayIndex(int nextPreferredStartDayIndex) {
this.nextPreferredStartDayIndex = nextPreferredStartDayIndex;
}
public int getPrevPreferredStartDayIndex() {
return prevPreferredStartDayIndex;
}
public void setPrevPreferredStartDayIndex(int prevPreferredStartDayIndex) {
this.prevPreferredStartDayIndex = prevPreferredStartDayIndex;
}
// ===================== COMPLEX METHODS ===============================
public int getCurrOrPrevPreferredStartDayIndex() {
return (isPreferredSequenceStart() ? dayIndex : prevPreferredStartDayIndex);
}
public int getCurrOrNextPreferredStartDayIndex() {
return (isPreferredSequenceStart() ? dayIndex : nextPreferredStartDayIndex);
}
public int getCurrOrPrevPreferredEndDayIndex() {
return (isPreferredSequenceEnd() ? dayIndex : (isPreferredSequenceStart() ? dayIndex-1 : prevPreferredStartDayIndex-1));
}
public int getCurrOrNextPreferredEndDayIndex() {
return (isPreferredSequenceEnd() ? dayIndex : nextPreferredStartDayIndex-1);
}
public boolean isNoNextPreferred() {
return getNextPreferredStartDayIndex() == noNextPreferredDayIndex;
}
public boolean isNoPrevPreferred() {
return getPrevPreferredStartDayIndex() == noPrevPreferredDayIndex;
}
/**
* #return if this is a preferred start date, then the sequence length that will fill from this date through the next end date; otherwise the days filling the past preferred start date through next end date
*/
public int getPreferredCoveringLength() {
if (isPreferredSequenceStart()) {
return nextPreferredStartDayIndex - dayIndex;
}
return nextPreferredStartDayIndex - prevPreferredStartDayIndex;
}
/**
* #return if this is a preferred start boundary, then "today", else day of most recent start boundary
*/
public DayOfWeek getPreferredStartDayOfWeek() {
if (isPreferredSequenceStart()) {
return getDayOfWeek();
}
if (isNoPrevPreferred()) {
throw new IllegalStateException("No prev preferred day of week available for " + toString());
}
return date.minusDays(dayIndex - getPrevPreferredStartDayIndex()).getDayOfWeek();
}
public DayOfWeek getPreferredEndDayOfWeek() {
if (isPreferredSequenceEnd()) {
return getDayOfWeek();
}
if (isNoNextPreferred()) {
throw new IllegalStateException("No next preferred day of week available for " + toString());
}
return date.plusDays((getNextPreferredStartDayIndex()-1) - dayIndex).getDayOfWeek();
}
public DayOfWeek getDayOfWeek() {
return date.getDayOfWeek();
}
public int getMostRecentDayIndexOf(DayOfWeek targetDayOfWeek) {
return dayIndex - getBackwardDaysToReach(targetDayOfWeek);
}
public int getUpcomingDayIndexOf(DayOfWeek targetDayOfWeek) {
return dayIndex + getForwardDaysToReach(targetDayOfWeek);
}
public LocalDate getMostRecentDateOf(DayOfWeek targetDayOfWeek) {
return date.minusDays(getBackwardDaysToReach(targetDayOfWeek));
}
public LocalDate getUpcomingDateOf(DayOfWeek targetDayOfWeek) {
return date.plusDays(getForwardDaysToReach(targetDayOfWeek));
}
public int getForwardDaysToReach(DayOfWeek targetDayOfWeek) {
return getForwardDaysToReach(this.getDayOfWeek(), targetDayOfWeek);
}
public static int getForwardDaysToReach(DayOfWeek startDayOfWeek, DayOfWeek targetDayOfWeek) {
if (startDayOfWeek == targetDayOfWeek) {
return 0;
}
int forwardDayCount = 1;
while (startDayOfWeek.plus(forwardDayCount) != targetDayOfWeek) {
forwardDayCount++;
if (forwardDayCount > 10) {
throw new IllegalStateException("counting forward in days from " + startDayOfWeek + " never found target day of week: " + targetDayOfWeek);
}
}
return forwardDayCount;
}
public int getBackwardDaysToReach(DayOfWeek targetDayOfWeek) {
return getBackwardDaysToReach(this.getDayOfWeek(), targetDayOfWeek);
}
public static int getBackwardDaysToReach(DayOfWeek startDayOfWeek, DayOfWeek targetDayOfWeek) {
if (startDayOfWeek == targetDayOfWeek) {
return 0;
}
int backwardDayCount = 1;
while (startDayOfWeek.minus(backwardDayCount) != targetDayOfWeek) {
backwardDayCount++;
if (backwardDayCount > 10) {
throw new IllegalStateException("counting backward in days from " + startDayOfWeek + " never found target day of week: " + targetDayOfWeek);
}
}
return backwardDayCount;
}
public String getLabel() {
return date.format(LABEL_FORMATTER);
}
#Override
public String toString() {
return date.format(DateTimeFormatter.ISO_DATE);
}
}
If the same object being tested in the rule can match in multiple parts of an 'or' condition, then Optaplanner throws this IllegalStateException, at least through 7.15.0. See details explored in optaplanner jira 1433.
Workaround is to always add terms to later terms of 'or' expressions that ensure the matching object can not be the same one that matched earlier parts of the 'or'. For the original posting above, the 'preferredSequenceStart == true' achieved this exclusion.
Note that the use of the 'exists' keyword in the terms of the 'or' can cause trouble with this workaround; try to avoid using 'exists' in this situation.

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.

Next day check by using calendar JSF primefaces

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();");
}
}

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);
}});