How can I access a domain property using the property name? - grails

I have a domain object with a property called date:
class Item implements Comparable{
Date date
}
How can I access that date doing something like:
Item.list().each{
Date d = it.get("date")
}
I know that I could do Date d = it.date but I want to be able to generically pick a property from my domain object and access it without using .property.

This should also work:
String propertyName = 'date'
Item.list().each {
Date d = it."$propertyName"
}

Try this..,.
Item.list().each {
Date d = it.properties.get("date")
}
or
Item.list().each {
Date d = it.getProperty("date")
}

Related

How to give a date Format to the sting parameter in query string? [duplicate]

I have to convert string in mm/dd/yyyy format to datetime variable but it should remain in mm/dd/yyyy format.
string strDate = DateTime.Now.ToString("MM/dd/yyyy");
Please help.
You are looking for the DateTime.Parse() method (MSDN Article)
So you can do:
var dateTime = DateTime.Parse("01/01/2001");
Which will give you a DateTime typed object.
If you need to specify which date format you want to use, you would use DateTime.ParseExact (MSDN Article)
Which you would use in a situation like this (Where you are using a British style date format):
string[] formats= { "dd/MM/yyyy" }
var dateTime = DateTime.ParseExact("01/01/2001", formats, new CultureInfo("en-US"), DateTimeStyles.None);
You need an uppercase M for the month part.
string strDate = DateTime.Now.ToString("MM/dd/yyyy");
Lowercase m is for outputting (and parsing) a minute (such as h:mm).
e.g. a full date time string might look like this:
string strDate = DateTime.Now.ToString("MM/dd/yyyy h:mm");
Notice the uppercase/lowercase mM difference.
Also if you will always deal with the same datetime format string, you can make it easier by writing them as C# extension methods.
public static class DateTimeMyFormatExtensions
{
public static string ToMyFormatString(this DateTime dt)
{
return dt.ToString("MM/dd/yyyy");
}
}
public static class StringMyDateTimeFormatExtension
{
public static DateTime ParseMyFormatDateTime(this string s)
{
var culture = System.Globalization.CultureInfo.CurrentCulture;
return DateTime.ParseExact(s, "MM/dd/yyyy", culture);
}
}
EXAMPLE: Translating between DateTime/string
DateTime now = DateTime.Now;
string strNow = now.ToMyFormatString();
DateTime nowAgain = strNow.ParseMyFormatDateTime();
Note that there is NO way to store a custom DateTime format information to use as default as in .NET most string formatting depends on the currently set culture, i.e.
System.Globalization.CultureInfo.CurrentCulture.
The only easy way you can do is to roll a custom extension method.
Also, the other easy way would be to use a different "container" or "wrapper" class for your DateTime, i.e. some special class with explicit operator defined that automatically translates to and from DateTime/string. But that is dangerous territory.
Solution
DateTime.Now.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture)
I did like this
var datetoEnter= DateTime.ParseExact(createdDate, "dd/mm/yyyy", CultureInfo.InvariantCulture);
You can change the format too by doing this
string fecha = DateTime.Now.ToString(format:"dd-MM-yyyy");
// this change the "/" for the "-"
The following works for me.
string strToday = DateTime.Today.ToString("MM/dd/yyyy");

Grails: Find class property based on Date

I have a Grails 2.4.3 application that uses Oracle as the database.
There's a class called User:
class User {
String userName = ""
String userPassword = ""
Date userAdded
}
In a controller i am using the following code to find all user names.
def names = User.where { }.projections { property 'userName' }.list()
Now i want to find User Names based on the date in which they were added to database.
For e.g., if a date range is provided as between 12/01/2014 to 12/12/2014, Now i want to get all the User Names added during that period.
Is there a easy way of doing it?
This should do it
Date start = // get the start date
Date end = // get the end date
def userNames = User.withCriteria {
ge('userAdded', start)
le('userAdded', end)
projections {
property("userName")
}
}

java.lang.NullPointerException in command object

I want to parse a string to date just before validate a command object, here is my command object code
class ActivitiesCommand {
List schools
List departments
Date from
Date to
static constraints = {
schools nullable:false
departments nullable:false
from blank:false
to blank:false
}
def beforeValidate() {
def from = new Date().parse("yyyy-MM-dd", from)
def to = new Date().parse("yyyy-MM-dd", to)
}
}
but i am getting java.lang.NullPointerException when i try def from = new Date().parse("yyyy-MM-dd", from) or def to = new Date().parse("yyyy-MM-dd", to). What can i do in order to successfully parse the date before validate command object?
I read the command object docs. I got this sample from there. I tried if removing ? beforeValidate does not work, so i understand i need to provide a null safe but i do not know how to do it in my scenario
class Person {
String name
static constraints = { name size: 5..45 }
def beforeValidate() { name = name?.trim() }
}
Thanks for your time.
from and to is set to Date in the Command Object, so request parameter string with from and to names will be converted to a Date and then bound to these field.
If the expected date format matches then binding will be successful.
In your case, from and to in beforeValidate is treated as String instead. If they are String actually then you can make them nullable: false in constraints or do the check as below in beforeValidate:
from = from ? Date.parse("yyyy-MM-dd", from) : new Date() - 1 //for example
Note the appropriate use of Date.parse()

Setting default value for Date field in Grails Domain Class

I'm trying to set a default value for a Date field in a Domain class.
I can use defaultValue in the mapping configuration but it doesn't work with Date fields (I've tried it on String and Integer and it works fine).
This is an example:
class Something {
Date myField
static mapping = {
myField defaultValue: new Date()
}
}
This code fails because the CREATE statement that Hibernate generates is incorrect. It is something like:
... my_field datetime default Mon Nov 25 17:59:08 UYST 2013 not null ...
You can always initialize the field in the static initializer or set the value in the constructor:
class Something {
// initializer
Date myField = new Date()
// or in the ctor
Something() {
myField = new Date()
}
}
This doesn't set a default value in the database schema, it merely sets the value of the field on creation of the instance. If you want the schema to have a default value, you can use the 'defaultValue' mapping entry like so:
class Something {
Date myField
static mapping = {
myField defaultValue: "now()"
}
}
the value you set for the default value is dependent on your database vendor. (notice the use of sql now() method rather than Java/Groovy new Date().
GORM readily caters for the most basic Date use cases; create and update.
Simply include keywords dateCreated and lastUpdated into the domain's properties for the default functionality to occur.
Warning: If their constraints are nullable: false this will cause a fail. Either remove those constraints or set autoTimestamp to false.
For example:
class MyDomain {
Date dateCreated
Date lastUpdated
Date yesterday = new Date().previous()
Date weekAgo = new Date() - 7
Date monthAgo = new Date() - 30
Date usaIndepenceDay = new Date().copyWith(
year: 1776,
month: Calendar.JULY,
dayOfMonth: 4,
hourOfDay: 0,
minute: 0,
second: 0)
static mapping = {
//autoTimestamp false
}
static constraints = {
//dateCreated nullable: false
}
}
Read the more about groovy dates at this SO answer, the groovy date api, and GORM's date-event features here
You can use this for default crated date auto get from system date
class User {
String userName
String firstName
String lastName
Date createdDate = new Date() // set system date
static mapping = {
version false
id generator: 'increment'
cache true
}
static constraints = {
userName(unique: true)
}
}

Groovy Dynamic Object - How to properly reset properties?

Based on this question I created a Groovy class that will have dynamic properties.
class MyDynamic {
def propertyMissing( String name, value ) {
this.metaClass."$name" = value
value
}
}
So far all good, now I can set some non-existent property with success
MyDynamic dyna = new MyDynamic()
dyna.someProp = new Date()
My problem begins when I have another instance with the same name of property, but with another type
MyDynamic dyna2 = new MyDynamic()
dyna2.someProp = "0" //GroovyCastException: Cannot cast object '0' with class 'java.lang.String' to class 'java.util.Date'
Actually I need this because I'm creating objects with the result of a query without knowing the table and the column. I get the name of the column with the ResultSetMetaData and add the property to the instance of the dynamic object. Later I will use this object to export all the properties and values. In different tables I have the same column name, but with different types.
So my question is: how can I reset this metaClass when I'm done with the instance to not conflict with other instance?
Why not a Expando, a Map or a simple container:
class Dynamic {
def properties = [:]
void setProperty( String name, value ) {
properties[name] = value
}
def getProperty(String property) { properties[property] }
}
d = new Dynamic()
d.name = "yeah"
assert d.name.class == String
d.name = new Date()
assert d.name.class == Date

Resources