Google App Engine Query Execute only takes 3 arguments - java

Can anyone tell me why the following code is causing an error on the last line with the command "execute" with the error message:
The method execute(Object, Object, Object) in the type Query is not applicable for the arguments (Long, Long, Date, Date)
Query q = pm.newQuery(Appointment.class,"AdminID == AID"+
" && EmployeeID == CEID"+
" && Time > STime"+
" && Time < ETime");
q.declareImports("import java.util.Date");
q.declareParameters("Long AID, Long CEID, Date STime, Date ETime");
q.setOrdering("Time");
Appointments = (List<Appointment>) q.execute(AdminID, CurrentEmployeeID, Time1, Time2);
As far as I can tell (implied by the error message, the execute function can only take a maximum of 3 arguements, if this is the case, can anyone advise on how to achieve what I want to do? I have tried the following code, but I get a parsing error every time it runs!
Query q = pm.newQuery(Appointment.class,"AdminID == "+AdminID+
" && EmployeeID == "+CurrentEmployeeID+
" && Time > "+Time1+
" && Time < "+Time2);
q.declareImports("import java.util.Date");
q.setOrdering("Time");
Appointments = (List<Appointment>) q.execute();
The Parsing error I get is:
org.datanucleus.store.query.QueryCompilerSyntaxException: Portion of expression could not be parsed: Aug 13 11:44:55 BST 2012 && Time < Mon Aug 13 11:45:05 BST 2012

Try executeWithArray or executeWithMap.
HashMap<String, Object> params = new HashMap<String, Object>();
params.put( "AID", adminId );
params.put( "CEID", currentEmployeeId );
params.put( "STime", startTime );
params.put( "ETime", endTime );
query.executeWithMap( params );
Notes:
variables should be lowerCamelCase
startTime and endTime are more descriptive than Time1, Time2
"Id" is generally preferred over "ID" - What is correct Java naming convention for id?
your second attempt won't work because it's implicitly calling ..." && Time > " + Time1.toString() + ...

Related

How do I set a default time to my timepicker?

I have I time picker in my code and when I press the edit text it shows up and everything looks good but I want to set a default time for my time picker so when the user opens the time picker it will be shown a specific time like "3:34 am" as a default time for the user, how can I do that?. Any help will be appreciated. { you can use java and kotlin}
My time picker
private fun showTimePicker() {
picker = MaterialTimePicker.Builder()
.setTimeFormat(TimeFormat.CLOCK_12H)
.setHour(12)
.setMinute(0)
.setTitleText("حدد الموعد الذي تريدة")
.build()
picker.show(supportFragmentManager, "AdhanNotifacations")
picker.addOnPositiveButtonClickListener {
if (picker.hour > 12) {
fajrEditTxt.setHint(String.format("%02d", picker.hour - 12) + ":"
+ String.format("%02d", picker.minute) + " PM")
} else {
fajrEditTxt.setHint(String.format("%02d", picker.hour) + ":"
+ String.format("%02d", picker.minute) + " AM")
}
calender = Calendar.getInstance()
calender[Calendar.HOUR_OF_DAY] = picker.hour
calender[Calendar.MINUTE] = picker.minute
calender[Calendar.SECOND] = 0
calender[Calendar.MILLISECOND] = 0
}
}
You were almost there, just change the value of setHour and setMinute to the hour and minute you want respectively.
I made few changes to your code to show default time of 3:34am:
picker = MaterialTimePicker.Builder()
.setTimeFormat(TimeFormat.CLOCK_12H)
.setHour(3) //3 hour
.setMinute(34) //34 minutes, so 3:34am
.setTitleText("حدد الموعد الذي تريدة")
.build()
If you want to show hour in PM, just add 12 to the hour. For example:
setHour(15)// will show 3pm
Let me know if you have any questions. Thanks.
EDIT
If you want to show time in strict HH:MM format you can keep your code and go as-is. But if you do not wish to be strict, then use the following code:
For example, this will show 9:3PM instead of 09:03PM.
//removed unnecesarry String.format
if(picker.hour > 12){
fajrEditTxt.setHint((picker.hour - 12).toString() + ":" + (picker.minute).toString() + " PM")
}else{
fajrEditTxt.setHint((picker.hour).toString() + ":" + (picker.minute).toString() + " AM")
}
OP asked how to access time:
val time = if(picker.hour > 12){
String.format("%02d",picker.hour - 12) + ":" + String.format("%02d", picker.minute) + " PM"
}else{
String.format("%02d",picker.hour) + ":" + String.format("%02d", picker.minute) + " AM"
}
time //use time, its in HH:MM format
fajrEditTxt.setHint(time)
I'm not understanding what it is you're asking, but if you're trying to sort the times in the library, you could place the times in a list and then sort the list, or if you just want to compare the magnitude values of two different times with just a couple of lines of code, you could remove the time separators from the time strings, convert those values to numbers ( of your choice ) and compare. The numbers generated from the conversions have no real world values, but their magnitudes with respect to one another will always be valid.
Oh. Snippet editor does not support touch devices.
Ok then.
String time = "00:00";
time.replace( ":", "" );
Double d = Double.parseDouble( time );
So now you can do with d as you wish. As you can see you don't have to bother with whether any of the values are to great. If you're dealing with a pair of valid times it's their relative magnitudes that matters. Of course if the time is in 12 Hr format, you'll need to strip the time modifier ( A, a, P, p, Am, AM .... ) too.

Convert the format of a date in Java/Typescript for searchpurposes

I search for a while now, but I didn't found what I need to solve my problem.
First of,I have a "add reminder page" in my app to add reminder with some inputs and the date / time:
<ion-row>
<ion-col>
<ion-label class="ion-label-links" >{{"Datum"|translate}}</ion-label>
</ion-col>
<ion-col text-right>
<ion-label class="ion-label-reminder-rechts">{{"Uhrzeit"|translate}}</ion-label>
</ion-col>
</ion-row>
<ion-row class="schnurr">
<ion-col>
<ion-datetime class="ion-input-reminder" displayFormat="DD.MM.YYYY" [(ngModel)]="reminder.myDate" ></ion-datetime>
</ion-col>
<ion-col>
<ion-datetime text-right class="ion-input-reminder-r" displayFormat="HH:mm" minuteValues="0,5,10,15,20,25,30,35,40,45,50,55" [(ngModel)]="reminder.myTime" ></ion-datetime>
</ion-col>
</ion-row>
And I set a standard date/time with this function:
formatLocalDate() {
var now = new Date(),
tzo = -now.getTimezoneOffset(),
dif = tzo >= 0 ? '+' : '-',
pad = function(num) {
var norm = Math.abs(Math.floor(num));
return (norm < 10 ? '0' : '') + norm;
};
return now.getFullYear()
+ '-' + pad(now.getMonth()+1)
+ '-' + pad(now.getDate())
+ 'T' + pad(now.getHours())
+ ':' + pad(now.getMinutes())
+ ':' + pad(now.getSeconds())
+ dif + pad(tzo / 60)
+ ':' + pad(tzo % 60);
}
Okay, everything is fine. I Save the record in my couchDb and it looks like this:
2017-07-05T09:18:24+02:00
Now the problem with this kind of format is that I implemented a search field but the usual format here is "dd.mm.yyyy" and not the ISO format, so I formated the output in my app like this:
<br><font size="1">{{item.doc.myDate | date:'dd.MM.yyyy, HH:mm'}} Uhr</font>
but if I search for that item, it doesn't work, because the variable is still in the old format.
My search is looking like this:
.....
<ion-item *ngIf="!searchvariable || item.doc.xName.toLowerCase().includes(this.searchvariable)
|| item.doc.myDate.toDateString().includes(this.searchvariable)" class="ion-item1" tappable (click)="openReminder(reminder.doc)" style="background-color: oldlace">
{{item.doc.myDate.toDateString()}}
......
The search is working for everything but the date. (because of the formatproblems)
Is there a possibility to do something like "reminder.myDate.format(xxx)" or something like this?
I mean, it's possible to alter the output, is there a similar way for my search?!
Btw. I have to format the date with this function, otherwise I get errors because the datepicker needs this format.
Thank you!

Conversion from "datetime-local" to java.sql.Timestamp

I have a form with input of type "datetime-local" on a jsp page, the data is passed to a servlet:
String resetTimeString = request.getParameter(RequestParameterName.RESET_TIME);
How to convert the input to java.sql.Timestamp?
EDIT:
Well, I found something new!
You can use Timestamp.valueOf() to format a time-string with the value of yyyy-[m]m-[d]d hh:mm:ss[.f...]
So it can also handle micro/nano seconds. The only thing you need to do is replace the T with a space.
This works:
String datetimeLocal = "1985-04-12T23:20:50.52";
System.out.println(Timestamp.valueOf(datetimeLocal.replace("T"," ")));
The output:
1985-04-12 23:20:50.52
According to this site your resetTimeString looks like this: '1985-04-12T23:20:50.52' (a string)
I couldn't find a method to convert this to a timestamp directly, but you could just split it up manually:
String[] dateTime = datetimeLocal.split("T");
String[] date = dateTime[0].split("-");
String[] time = dateTime[1].split(":");
This will print:
System.out.println("DateTime: " + Arrays.toString(dateTime));
System.out.println("Date: " + Arrays.toString(date));
System.out.println("Time: " + Arrays.toString(time));
>>> DateTime: [1985-04-12, 23:20:50]
>>> Date: [1985, 04, 12]
>>> Time: [23, 20, 50]
After that you could just create a new Timestamp: (This is deprecated!)
Timestamp stamp = new Timestamp(Integer.valueOf(date[0]).intValue() - 1900,
Integer.valueOf(date[1]).intValue(),
Integer.valueOf(date[2]).intValue(),
Integer.valueOf(time[0]).intValue(),
Integer.valueOf(time[1]).intValue(),
Integer.valueOf(time[2].split("\\.")[0]).intValue(),
Integer.valueOf(time[2].split("\\.")[1]).intValue());
Note that, if you use this you need to subtract '1900' from the year and split dots with \\.
Also, you'd need to handle nanoseconds (In my example I'm using the value 50.52 as seconds, but the string returned from your server might not contain the nanoseconds)
You could also calculate a long from the date and use new Timestamp(<long>)
I hope this helps :)
Cyphrags' answer won't work if seconds are set to "00", because Chrome won't send the seconds part resulting in a java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff] when calling Timestamp.valueOf().
Therefore a more complete answer could be:
String datetimeLocal = "1985-04-12T23:20";
// make sure the seconds are set before parsing
if (StringUtils.countMatches(datetimelocal, ":") == 1) {
datetimelocal += ":00";
}
Timestamp value = Timestamp.valueOf(datetimeLocal.replace("T", " "));

Java7 GregorianCalendar timeInMillis from collection are not working well

I need to record a collection of objects that keep: Date, and average Day temperature.
and I need to be able to track back the date.
So I created a class that keeps these values and I made an ArrayList that keeps these objects.
In my code I test to keep 5 days. When I run the program and the ArrayList gets filled everything seems fine and the terminal displays:
dateSaved:2013-10-16 11:59:59 TimeStamp: 1381960799018
dateSaved:2013-10-17 11:59:59 TimeStamp: 1382047199018
dateSaved:2013-10-18 11:59:59 TimeStamp: 1382133599018
dateSaved:2013-10-19 11:59:59 TimeStamp: 1382219999018
These TimeStamps are all unique and seem to be fine.
however when I then enter the for loop and want to get the timestamps from each of these entries I get:
entry: 0 //removed since the first dateSaved has not been pasted*
entry: 1 timeInMillis: 1382306399018
entry: 2 timeInMillis: 1382306399018
entry: 3 timeInMillis: 1382306399018
entry: 4 timeInMillis: 1382306399018
These are all the same times and are: Sun, 20 Oct 2013 21:59:59 GMT
That is the date here. but not the time. And i'm not realy getting the values I expect to get.
What is going wrong here?
GregorianCalendar date = new GregorianCalendar();
GregorianCalendar beginDate = new GregorianCalendar();
beginDate.roll(beginDate.DAY_OF_YEAR ,-5);
while(beginDate.getTimeInMillis() < date.getTimeInMillis() )
{
GCalAndDouble dateAndTemp = new GCalAndDouble(beginDate, WeatherStation.Instance().getValue(Enums.MeasurementType.outsideTemperature, Enums.ValueType.average, beginDate) );
list.add(dateAndTemp);
System.out.println("dateSaved:" + new SimpleDateFormat("YYYY-MM-dd KK:mm:ss").format(new Timestamp(beginDate.getTimeInMillis())) + " TimeStamp: " + beginDate.getTimeInMillis() );
long timeTemp = beginDate.getTimeInMillis();
beginDate.setTimeInMillis(timeTemp + 86400000); // + the ammount of milliseconds in a day.
}
for(int j = 0; j < 5; j++)
{
GCalAndDouble tempdateandtemp = list.get(j);
long timestamptemp = tempdateandtemp.getDate().getTimeInMillis();
System.out.println("entry: " + j + " timeInMillis: " + timestamptemp);
}
Thanks for your help!
You are using the same beginDate object. This means that all the values will be the same. They might have changed as you were building the list, but the final value is all you will see.
Most likely you intended to create a new Date() object for each entry to give each one a different Date. BTW I prefer to use long which is not only more efficient but doesn't have this issue.

Halting program execution between certain hours of the week

I am writing a Java program that is required to copy files and folders between the following hours:
Mon - 18:00 to 06:30
Tue - 18:00 to 06:30
Wed - 18:00 to 06:30
Thu - 18:00 to 06:30
Fri - 18:00 to 06:30
Sat - all day
Sun - all day
The program will run continuously until it has finished copying all files and folders. However, outside of the above hours the program should just sleep.
I am using a properties file to store the above settings.
UPDATE
I am looking for the simplest possible implementation including the format of the properties in the properties file as well as the code that will make the checks.
I would do it like this
final Map<Integer, String> schedule = new HashMap<>();
// parse your settings and fill schedule
schedule.put(Calendar.MONDAY, "18:00 to 06:30");
// ...
// create timer to fire e.g. every hour
new Timer().scheduleAtFixedRate(new TimerTask() {
public void run() {
Calendar c = Calendar.getInstance();
String s = schedule.get(c.get(Calendar.DAY_OF_WEEK));
if (withinTimeRange(c, s)) { // implement withinTimeRange func
// copy files
}
}}, 0, 1000 * 3600);
Since your program is going to run continuously, the simplest solution is to check the day and time before copying a file. If the time is during off hours, go ahead and copy the next file, otherwise Thread.sleep.
If this is an internal, one-off kind of program, I would go ahead and hard-code the business hours instead of reading the properties file. No need to add complexity.
whenever your program is launched, get the current time, and check day today's day.
check whether it lies in permissible time if yes let it continue. If not, find the time at 00:00am of that 'day'. and find the time at xx:yyZZ (start of permissible time). calculate the difference, and let the program sleep for that much of time.
Thank you for your suggestions.
I came up with a working solution in the end which if it gets enough points I will mark as the answer. The way I attempted to solve this problem was by thinking about non-working hours rather than working hours. This code is just for illustration
# Properties
Mon = 06:30-18:00
Tue = 06:30-18:00
Wed = 06:30-18:00
Thu = 06:30-18:00
Fri = 06:30-18:00
Loop over the properties to get their values
String[] days = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
Map<Integer, Integer[]> nonWorkingHours = new HashMap<Integer, Integer[]>();
for( int i = 0; i < days.length; i++ ) // for each property in file
{
// excluded implementation of getConfig
String prop = getConfig( days[ i ] ); // e.g. "06:00-19:00"
// +1 to match CALENDAR.DAY_OF_WEEK
nonWorkingHours.put( i + 1, getHours( prop );
}
My function to parse property excluding error handling
// e.g. if prop = "06:00-19:00" then { 6, 0, 19, 0 } is returned
public Integer[] getHours( String prop )
{
String times = prop.split( "(:|-)" );
Integer[] t = new Integer[4];
for( int i = 0; i < times.length; i++ )
{
t[i] = Integer.parseInt( times[i] );
}
return t;
}
And finally the function that implements the halt
private void sleepIfOutsideWorkingHours()
{
Integer[] data = nonWorkingHours.get( currentDay );
if( data != null )
{
Calendar c = Calendar.getInstance();
Integer currentSeconds = ( Calendar.HOUR_OF_DAY * 3600 ) + ( Calendar.MINUTE * 60 );
Integer stopFrom = ( data[ 0 ] * 3600 ) + ( data[ 1 ] * 60 );
Integer stopTill = ( data[ 2 ] * 3600 ) + ( data[ 3 ] * 60 );
if( currentSeconds > stopFrom && currentSeconds < stopTill )
{
Integer secondsDiff = stopTill - currentSeconds;
if( secondsDiff > 0 )
{
try
{
Thread.sleep( secondsDiff * 1000 ); // turn seconds to milliseconds
}
catch( InterruptedException e )
{
// error handling
}
}
}
}
}
And finally just call the function below just before copying each file and if it is being run outside working hours it will stop the program.
sleepIfOutsideWorkingHours();
I am sure there is a simpler way of doing it :-) but there it is.
You should try using a Continuous Integration system. That scenario can be easily set up using Jenkins CI for example.
The reason i advise doing it so in a ambient like that is that you can keep a better control on the history of your program runs.

Categories