How to bind multiple form elements to a single variable with the Play! framework - frameworks

I am using the Play! framework, version 1. I have a form with 3 different select elements for day, month and year. I want to bind these to the birth date of a user (public Date birthDate defined in class User). How can I do this? Thanks.

You can create three setters getters in your class for day, month and year and update your date with these values. The best way to do that is to use joda date classes
public class MyClass {
public DateMidnight birthDate;
public int getBirthDateYear() {
return birthDate.getYear();
}
public void setBirthDateYear(int year) {
birthDate = birthDate.withYear(year);
}
}
and same thing with "monthOfYear" and "dayOfMonth"

I don't think it's worth fussing about with anything in the model, play can do this all in the controller, it's a bit of logic but should be no big deal in a smaller app. Assuming your select boxes POST numbers in your controller and you send other user stuff that mapped properly by name to user properties:
public static void save(User user, String day, String month, String year) {
DateFormat formatter = new SimpleDateFormat("MMddyy");
Date birthDate = formatter.parse(month + day + year);
user.birthDate = birthDate;
user.save();
}

Related

JPA Projection spring boot; repository mapping entity instant to do date

I have an entity that has a date modelled as an Instant
I have an DO object that has a date modelled as a Date
when i do the conversion myself in the constructor of the DO it works:
public class DO {
private Date someTimePoint;
public DO(Instant CreatedAt) {
this.someTimePoint = Date.from(CreatedAt);
}
}
and my repo works call:
List<DO> findBySomeField(UUID someField);
Give result.
However: The DO is generated and I do not have access to it, so the constructor is actually:
public DO(Date CreatedAt) {
So the question is:
Is there a way to have the conversion from Instant to Date done on the fly by Spring using the Projection methodology?
Reading https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections
doesn't give me any clues...

Comparing LocalDate with date part of LocalDateTime in apache ignite

I have a certain records in ignite cache and I want to retrieve all records for current day. For this I need to compare LocalDateTime type field of cached object with Localdate object i.e LocalDate.now(). How do I write a query to do this. In oracle TODATE(date, format) does the same thing but this function is not present in H2.
cached field datetime: 2016-08-30T05:31
date instance : 2016-08-30
SQL will be like
String sql = "select * from cacheName where date='convert(datetime) to date'";
Is it possible in H2 ?
You can use custom SQL functions for this: https://ignite.apache.org/releases/mobile/org/apache/ignite/cache/query/annotations/QuerySqlFunction.html
For example, if your value class looks like this:
public class MyValue {
#QuerySqlField
private LocalDateTime time;
public MyValue(LocalDateTime time) {
this.time = time;
}
}
You can create a function like this:
public static class MyFunctions {
#QuerySqlFunction
public static String toDate(LocalDateTime time) {
return time.format(DateTimeFormatter.ISO_LOCAL_DATE);
}
}
And provide it in the configuration like this:
cacheCfg.setSqlFunctionClasses(MyFunctions.class);
The query will look like this:
select * from MyValue where toDate(time) = '2016-08-30'

Swagger Model Schema Response: alternate label for LocalDate in SpringFox

We are using Swagger 2.x and SpringFox 2.0 to document our REST service created with Spring MVC.
We have a REST response with a property List<LocalDate> dates.
In the Model Schema of the response, the label for dates is shown as 'LocalDate'. That is not intended: we would like to have 'date' or 'yyyy-MM-dd' instead.
We have this class:
public class SayHelloResponse {
private List<LocalDate> dates;
private String message;
public SayHelloResponse(String message, LocalDate... dates) {
this.message = message;
this.dates = ImmutableList.copyOf(dates);
}
public List<LocalDate> getDates() {
return dates;
}
public String getMessage() {
return message;
}
}
That results in this Model Schema:
{
"dates": [
"LocalDate"
],
"message": "string"
}
In the Model Schema, I would like to have LocalDate as 'date' or 'yyyy-MM-dd'. The way to do this seems to be with com.wordnik.swagger.annotations.ApiModelProperty but this does not have any effect (it is being picked up, as when I add #ApiModelProperty(hidden=true) it is hidden).
I created a sample rest project that shows the issue.
Any ideas how I can change LocalDate to 'date' or 'yyyy-MM-dd' in the Model Schema of Swagger?
There is a method in Docket object to replace models called directModelSubstitute(). You can use it like this to substitute LocalDate to Date object:
Docket#directModelSubstitute(LocalDate.class, Date.class)
The only problem with it that I found is that you can't change the date format.
See A/Q section in the official Springfox documentation, specifically question "How do we use Java 8 types esply. LocalDateTime?"
This is recommended in the official Springfox documentation, but doesn't effect:
Docket(DocumentationType.SWAGGER_2)..build().directModelSubstitute(LocalDate.class, java.sql.Date.class)
This effect but change format to date-time instead of date:
Docket(DocumentationType.SWAGGER_2)..build().directModelSubstitute(LocalDate.class, java.util.Date.class);
That's why I use the last one and ignore time part.

How to convert java.util.Date to Java8 java.time.YearMonth

How can I best convert a java.util.Date to a Java 8 java.time.YearMonth?
Unfortunately the following throws a DateTimeException:
YearMonth yearMonth = YearMonth.from(date.toInstant());
results in:
java.time.DateTimeException: Unable to obtain YearMonth from TemporalAccessor: 2015-01-08T14:28:39.183Z of type java.time.Instant
at java.time.YearMonth.from(YearMonth.java:264)
...
I need this functionality since I want to store YearMonth values in a database using JPA. Currently JPA does not support YearMonth's, so I've come up with the following YearMonthConverter (imports omitted):
// TODO (future): delete when next version of JPA (i.e. Java 9?) supports YearMonth. See https://java.net/jira/browse/JPA_SPEC-63
#Converter(autoApply = true)
public class YearMonthConverter implements AttributeConverter<YearMonth, Date> {
#Override
public Date convertToDatabaseColumn(YearMonth attribute) {
// uses default zone since in the end only dates are needed
return attribute == null ? null : Date.from(attribute.atDay(1).atStartOfDay(ZoneId.systemDefault()).toInstant());
}
#Override
public YearMonth convertToEntityAttribute(Date dbData) {
// TODO: check if Date -> YearMonth can't be done in a better way
if (dbData == null) return null;
Calendar calendar = Calendar.getInstance();
calendar.setTime(dbData);
return YearMonth.of(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1);
}
}
Isn't there a better (cleaner, shorter) solution (for both directions)?
Short answer:
// From Date to YearMonth
YearMonth yearMonth =
YearMonth.from(date.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDate());
// From YearMonth to Date
// The same as the OP:s answer
final Date convertedFromYearMonth =
Date.from(yearMonth.atDay(1).atStartOfDay(ZoneId.systemDefault()).toInstant());
Explanation:
The JavaDoc of the YearMonth.from(TemporalAccessor)-method says:
The conversion extracts the YEAR and MONTH_OF_YEAR fields. The extraction is only permitted if the temporal object has an ISO chronology, or can be converted to a LocalDate.
So, you need to either be able to:
extract the YEAR and MONTH_OF_YEAR fields, or
you should use something that can be converted to a LocalDate.
Lets try it!
final Date date = new Date();
final Instant instant = date.toInstant();
instant.get(ChronoField.YEAR); // causes an error
This is not possible, an exception is thrown:
java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: Year
at java.time.Instant.get(Instant.java:571)
...
This means that alternative 1 goes out the window. The reason for is explained in this excellent answer about how to convert Date to LocalDate.
Despite its name, java.util.Date represents an instant on the time-line, not a "date". The actual data stored within the object is a long count of milliseconds since 1970-01-01T00:00Z (midnight at the start of 1970 GMT/UTC).
The equivalent class to java.util.Date in JSR-310 is Instant, thus there is a convenient method toInstant() to provide the conversion.
So, a Date can be converted to an Instant but that did not help us, did it?
Alternative 2 however proves to be successful. Convert the Instant to a LocalDate and then use the YearMonth.from(TemporalAccessor)-method.
Date date = new Date();
LocalDate localDate = date.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDate();
YearMonth yearMonth = YearMonth.from(localDate);
System.out.println("YearMonth: " + yearMonth);
The output is (since the code was executed in January 2015 ;):
YearMonth: 2015-01

Using an Arraylist in ILOG/ODM to loop through a set of records

I have a requirement to loop through a set of records and compare the start date in each record with current date and output a message in the Action part of the rule. I am trying to find out if I can use an arraylist in ILOG/ODM rule XOM and use it in the rule to loop through the set of records.
Can you please suggest me the best way to implement this requirement.
Yes, you can use an arraylist in rule XOM, and iterate over it in the rule. Let's assume your rule project takes an instance of your XOM class as an input parameter with the verbalization 'test'. You would have something like below.
XOM:
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class Test
{
private List<Record> recordList;
public Test()
{
}
public void setRecordList(List<Record> recordList)
{
this.recordList = recordList;
}
public List<Record> getRecordList()
{
return recordList;
}
public static int compareWithCurrentDate( Date date)
{
Calendar cal = Calendar.getInstance();
cal.setTime( date);
return cal.compareTo( Calendar.getInstance());
}
}
import java.util.Date;
public class Record
{
private Date startDate;
public Record()
{
}
public void setStartDate(Date startDate)
{
this.startDate = startDate;
}
public Date getStartDate()
{
return startDate;
}
}
BOM Verbalization:
# Record
Record#concept.label = record
Record.startDate#phrase.action = set the start date of {this} to {start date}
Record.startDate#phrase.navigation = {start date} of {this}
# Test
Test#concept.label = test
Test.compareWithCurrentDate(java.util.Date)#phrase.navigation = compare {0} with current date
Test.recordList#phrase.action = set the record list of {this} to {record list}
Test.recordList#phrase.navigation = {record list} of {this}
Rule:
definitions
set 'current record' to a record in the record lists of test ;
if
compare the start date of 'current record' with current date is not 0
then
print "" ;
You can follow the instructions in the ODM Blogs on developerWorks under "iterating over input parameters" topic.
It can be found here:
Iterating over Input Parameters
Basically you are going to a virtual method for your ArrayList to retrieve an entry at particular loop index. The virtual method will cast the entry before returning it, but from there you should be able to perform any rule on that object.
Note that you cannot use ArrayList as an input parameter for Dynamic XOM but you can use Arrays for input parameter with a Java XOM.