Grails: JSON to beans - custom field name - grails

In my Grails application for POST request I am receiving some data as JSON in with keys in broken English.
{
"emplId": "1234",
"emplyNm": "Priyank Thakkar"
}
I am translating this JSON to a Groovy bean
Employee.groovy
class Employee {
String id
String name
}
Now, Grails is forcing me to use same key names as attributes of my bean class and I don't intend to do that. (This is not a domain class, this is a bean.)
How do I achieve this mapping?

Use Grails Command Object.
http://docs.grails.org/latest/guide/single.html#commandObjects
Whether it is domain or other bean, instead of looking for an workaround to map request param empId into String id, corresponding Command objects are more efficient.

You can use BindUsing annotation, see here http://docs.grails.org/2.3.5/api/org/grails/databinding/BindUsing.html

Related

Check property is present by property name

I want to check is a string contains the name of a valid property of one of my entity class.
I've figured several keys but at the end i've been unable to make them work and even not sure what it the best practice to do this.
Thanks in advance
Every Grails domain object has an injected domainClass property which exposes a persistentProperties list. You can access the list of properties in this way:
def o = new MyDomain()
o.domainClass.persistentProperties
You can also retrieve this list from the Spring application context, which avoids the need for a domain class instance. Among the Spring beans created for each domain class (four beans for each domain) there is one that has the full name of your domain class with the suffix {{DomainClass}}. Assuming grailsApplication has been injected:
grailsApplication.mainContext.getBean("MyDomainDomainClass").persistentProperties
Within the persistentProperties list, you can search for a property with a given name as follows:
persistentProperties.find { it.name == nameToSearchFor }
Finally i decided to go with
MyClass.metaClass.properties.find { it.name == params.searchedColName }
I think is little better solution than #Andrew von Dollen proposal since i avoid playing with the spring context ... feel that is more groovier this way.

How do I change the name of a Grails domain class id field?

I have a Grails 2.2.3 domain class called FundType that I am trying to map to a legacy database table. It has two fields: code and description. I would like the id to be called code anytime I use the domain class and preferably on any of the generated scaffolding. But every time I use the name key on id I get this exception:
| Error 2013-07-24 09:38:44,855 [localhost-startStop-1] ERROR context.GrailsContextLoader - Error initializing the application: Error evaluating ORM mappings block for domain [com.company.scholallow.FundType]: null
Message: Error evaluating ORM mappings block for domain [com.company.scholallow.FundType]: null
This is what my domain class consists of:
class FundType {
String id
String description
static mapping = {
id column: 'fund_code', generator: 'assigned', name: 'code'
description column: 'fund_desc'
}
}
And anytime I am using a FundType instance I would like to call code like fundTypeInstance.code and NOT fundTypeInstance.id. This will make it more user friendly for me because I'm dealing with something called code, not id.
So I would like to know is what I'd like to do possible? And what am I doing wrong in my domain class that is causing this ORM mappings error?
Edit:
Okay, so I changed my domain class to the following and I am getting a FundType not found with ID null error.
class FundType {
String code
String description
static mapping = {
id generator: 'assigned', name: 'code'
code column: 'fund_code'
description column: 'fund_desc'
}
}
I added some sql logging to see what Hibernate is doing and this is what was output: select * from ( select this_.FUND_CODE as RTVFTYP1_1_0_, this_.FUND_DESC as RTVFTYP2_1_0_ from RTVFTYP this_ ) where rownum <= ?
Use String code instead of String id in the domain class.
You are deliberately mentioning to the GORM that I want to use the property code which maps to table column fund_code whose value is assigned as the id (primary key). In that case, you just need to have the property codedefined in the domain class instead of the id.
(I'm answering the fix that worked for me for future use by other programmers)
#dmahapatro was right, I needed to add String code.
It looks like naming the id something different just doesn't play well with Grails dynamic scaffolding. I did some tests and I can still use FundType.get(code) and it will return the object just as if I passed in an id. I can also do FundType.findByCode(code).
It looks like I have to change the scaffolded controller to expect a String id instead of the default Long id. I also have to change the scaffolded list view to send fundTypeInstance.code instead of fundTypeInstance.id to the show controller, but I suspect that adding a getId() that just returns this.code will fix that.

spring MVC model attributes in jsp page

When I access simple model data like the username using : ${username} everything seems to be fine. But when I try to use ${userdata.uname} I get an error like :
Could not find property uname in class com.mydom.datahandling.userdata
userdata is java class I add to the ModelAndView
ModelAndView mav = new ModelAndView("page37");
mav.addObject("sessionID",ID);
mav.addObject("userdata",p37userdata);
What do I need to do differently ? This seems to be happening whenever I try to use something other than a primitive type or String. I obviously need a bit more education. Do I need to serialize p37userdata?
userdata is
public class userdata{
public String uname;
public String otherstuff;
}
The objects you reference from your EL in your JSP should be java beans (or a map). According to wikipedia (the source of all truth) A bean has the following properties:
They are serializable, have a 0-argument constructor, and allow access
to properties using getter and setter methods.
So you should probably add getters and setters to your userdata class.

how to parse XML in grails

I have object has XML as a string. For example I have a domain which has
class person{
String personId
String personName
String personType
String personDescription
String personDetailsXML
}
I am getting the details and binding to person object. I have to pass this object to another controller which displays the info about each person when he clicks on the profile name. How do i parse the XML string.
I have another domain say eachPerson domian which has
class eachPerson{
String personName
String personDescription
Object personDetails
I want to match the person name and person description and persondetailsXml.How do I do that and how can I parse personDetailsXML to personDetails object. Please suggest. How i can pass the personInstance as object to action show() in eachPerson controller??
I'd check this out for starters. Should be pretty straightforward to work from this example.
http://groovy.codehaus.org/Reading+XML+using+Groovy%27s+XmlParser.
(Upon re-reading, this doesn't entirely answer the question...)
You need to parse the xml (using introduced in the link in the comment above - or with XmlSlurper). This is pretty straightforward and easy to understand.
If you have all the data you can use render(action:'show', controller:'eachPerson', model:[persons:personsData]). See the grails doc for further details how to use render.
This will call the action with the given data. In the show action you can access it with params.persons.

Grails Acegi Plugin - PersonController.groovy - Please explain!

What does person.properties = params do?
Well, the short answer is that it matches any key in the params map with the properties of the person object, assigning the value in the params map to the property that matches.
example: Let's say params.id=156 and person has a member property named id. After this call, person.id would equal 156.
Some notes:
If there are keys in params that
don't match properties in person,
that's ok, it just won't do anything
with those.
If there are properties in person that don't have keys in params? Also
ok, it'll skip those too.
This is also very similar to creating a new Person via "new
Person( params )" or calling
"bindData( person, params )".
There is comprehensive documentation on the Grails web site
Behind the scenes, the properties on a Groovy/Grails object is a map of the domain class properties. The params object is also a map of the request parameters - basically the HttpServletRequest object CGI parameters. So the assignment will update the properties map with values from the params map, only where they match.
If you were to do this with straight Servlets & JSP's you would essentially be writing:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Person person = new Person();
person.firstName = request.getParameter('firstname');
person.lastName = request.getParameter('lastname');
person.password = request.getParameter('password');
...
}
With Grails, you would essentially just write this in PersonController.groovy:
def save = {
def person = new Person()
person.properties = params
...
}
So with Grails you don't need to worry too much about what the parameter names are since you should be using grails tags to output them and then the params mapping to get them back into the object. This lessens the stupid errors encountered when you mispel a parameter name.
You also can add more properties to the Person domain object and not have to write more getter/setter type statements.
It updates the property values on the person object using the supplied request parameters. This is called data binding and is documented here.

Resources