Map single controller to multiple methods/action - grails

My Controller name is ...Login...
and method/action names like....HomeContent.....automotive...etc
I am also posting my controller code here..
class LoginController {
def dataSource;
static allowedMethod = [userLogin:"POST",HomeContent:"GET",Disclaimer:"GET",FAQ:"GET",OurTeam:"GET",ourPortfolio:"GET",privacyPolicy:"GET",beautyTips:"GET",dietNutrition:"GET",healthFitness:"GET",yoga:"GET",mentalStress:"GET",automotive:"GET",digitalMarketing:"GET",ecommerce:"GET",education:"GET",finance:"GET",foodAndBeverage:"GET",marketUpdates:"GET",realState:"GET",coWorkingSpaces:"GET",homeRemodeling:"GET",scienceAndTechnology:"GET",sportsMania:"GET",travelAndTourism:"GET",boxOffice:"GET",dayToDayNewsUpdates:"GET",mediaGossip:"GET",poertyZone:"GET",lifestyleMagazine:"GET",becomeAContributor:"GET"]
def HomeContent()
{
def query ="SELECT id,post_title,post_date,post_content FROM wp_posts where post_status='publish' and post_type='post' ORDER BY post_date DESC limit 10"
def db = new Sql(dataSource)
def json = db.rows(query)
render json as JSON
}
// About Us section starts here
def Disclaimer()
{
def query = "select distinct id,post_title,post_date,post_content from wp_posts where post_title='disclaimer' and post_status='publish'"
def db = new Sql(dataSource)
def json = db.rows(query)
render json as JSON
}
def FAQ()
{
def query = "select distinct id,post_title,post_date,post_content from wp_posts where post_title='FAQ' and post_status='publish'"
def db = new Sql(dataSource)
def json = db.rows(query)
render json as JSON
}
and my URLMapping code here..
class UrlMappings {
static mappings = {
"/Login"(controller:"Login",action:"HomeContent")
"/"(view:"/index")
"500"(view:'/error')
}
}

Add generic support to UrlMappings, assuming that's all you want:
//inside static mappings:
"/$controller/$action?"{ }

Related

Grails console plugin (unexpected results)

I have the two domain clases:
class Persona {
String nombre
String apellidos
static hasMany = [pertenencias: Pertenencia]
static constraints = {
}
static mapping = {
pertenencias cascade: "all-delete-orphan"
}
}
class Pertenencia {
String nombre
static belongsTo = [persona:Persona]
static constraints = {
}
}
The service:
class MembresiaService {
#Transactional
def saveAll() {
def p = new Persona(nombre: 'carlos', apellidos: 'gm')
p.addToPertenencias(nombre: 'auto')
p.addToPertenencias(nombre: 'computadora')
p.addToPertenencias(nombre: 'casa')
p.save()
}
#Transactional
def deletePertenencias() {
def p = Persona.get(1)
p.pertenencias?.clear()
}
}
And the controller:
class TestController {
def membresiaService
def index() {}
def saveAll() {
membresiaService.saveAll()
redirect(action: "index")
}
def deletePertenencias() {
membresiaService.deletePertenencias()
redirect(action: "index")
}
}
When I execute saveAll() method from controller it saves the data in the database, when I execute deletePertenencias() from controller it deletes the "pertenecias" collection of Persona from the database (as expected).
I have installed the Grails console plugin , first time I execute the lines of saveAll() service method in the console, the result is the "persona" and its "pertenencias" in database. Then I execute the lines of deletePertenencias() service method in console but it doesn't delete the data of database and the "persona" object mantains the "pertenencias" (as if I had not run deletePertenencias() code).
Anyone kwnow why the code executed from console gives unexpected results?
I expect the result was the same from controller and console but the behaviour is different.

Cannot invoke method pullLogs() on null object when calling service in controller

I have search around stack overflow and have found some similar instances of my problem but there fixes done seem to work for mine. (example of simular one:Grails - Can't call service from Controller --> always get "Cannot invoke method on null object error")
My service can be summed up like this
class AuditService {
AuditService auditService
def sql
def dataSource
static transactional = true
def pullLogs(String username, String id) {
if(username != null && id != null) {
sql = new Sql(dataSource)
println "Data source is: " + dataSource.toString()
def schema = dataSource.properties.defaultSchema
sql.query('select USERID, AUDIT_DETAILS from DEV.AUDIT_LOG T WHERE XMLEXISTS(\'\$s/*/user[id=\"' + id + '\" or username=\"'+username+'\"]\' passing T.AUDIT_DETAILS as \"s\") ORDER BY AUDIT_EVENT', []) { ResultSet rs ->
while (rs.next()) {
def auditDetails = new XmlSlurper().parseText(rs.getString('AUDIT_EVENT_DETAILS'))
println auditDetails
}
}
sql.close()
}
}
}
The way im trying to call it is likes this
UserController {
def auditService
show(Long id){
def UserInstance = User.get(id)
//Also tried def auditResults = auditServices.pullLogs(UserInstance.username, UserInstance.id)
def auditResults = auditServices(UserInstance.username, UserInstance.id)
System.out.println(" "+ auditResults)
[UserInstance: UserInstance,params:params]
}
}
The error I get is
Class:
java.lang.NullPointerException
Message:
Cannot invoke method pullLogs() on null object
Im pretty stumped. (Query was given to me)
Any Ideas/Opnions/Help is greatly appriciated!
Thanks!
In UserController you have
def auditService
But then
def auditResults = auditServices(UserInstance.username, UserInstance.id)
which should be
def auditResults = auditService.pullLogs(UserInstance.username, UserInstance.id)
As for the "FactoryBean not initialized" error, for that you can simply remove the
AuditService auditService
from inside AuditService - it isn't necessary as you can just use this if you need a reference to AuditService from within its own code.
The name of your service is LogService or AuditService? If it's AuditService your attribute name in the controller have an s that shouldn't.
class UserController {
def auditService //Name should be the same of the service, not in plural
...
}

Deserialize a JSON object with support for embedded associations

Is there an easy way to deserialize a JSON string to a domain class with support of embedded association; belongsTo and hasMany
{
name: "Customer",
contact: {
name: "Contact"
}
}
class Customer {
name
Contact contact
}
class Contact {
String name
static belongsTo = [customer:Customer]
}
in my controller I would like to do the following
def save() {
def customer = new Customer(request.JSON)
customer.save();
}
Now i'm forced to do
def save() {
def contact = new Contact(request.JSON.contact);
def customer = new Customer(request.JSON);
customer.contact = contact;
customer.save();
}
Have you tried using JsonSlurper?
Example usage:
def slurper = new JsonSlurper()
def result = slurper.parseText('{"person":{"name":"Guillaume","age":33,"pets":["dog","cat"]}}')
assert result.person.name == "Guillaume"
assert result.person.age == 33
assert result.person.pets.size() == 2
assert result.person.pets[0] == "dog"
assert result.person.pets[1] == "cat"
Ref: http://groovy.codehaus.org/gapi/groovy/json/JsonSlurper.html
you can try this
Test test
def result = new JsonSlurper().parseTest('yourString')
test = result
Try this will work.

cannot set readonly property:params

i'm trying to save a picture and return it's visit-url,but system throw a exception about params: 'cannot set readonly property: params'
def upload() {
def attachmentInstance = new Attachment(utype:params.type, udata:params.data)
if (!attachmentInstance.save(flush: true)) {
render(view: "create", model: [attachmentInstance: attachmentInstance])
return
}
def subMap = [url:"${createLink(controller:'attachment', action:'renderImg', params:'[id:${attachmentInstance.id}]')}", width:0, height:0]
def jsonMap = [id:attachmentInstance.id, type:"image", thumbnail:"", data:subMap]
def result = [result:jsonMap]
render result as JSON
}
It looks a little over-complex, can you try:
def subMap = [url:createLink(controller:'attachment', action:'renderImg', params:[id:attachmentInstance.id]), width:0, height:0]

Grails controllers repeated code for all actions

Imagine this controller:
class exampleController{
def action1 = {}
def action2 = {}
def action3 = {}
def action4 = {}
def action5 = {}
}
I want to be able to return in all the action in this controller the same params. Imagining this:
def user = session.user
[user: user]
Is there any way of doing this, besides writing all the same code on all the actions? The session.user return params is just an example. I don't wanna really return it.
A simple solution is to put this code in a method and call it from each action
class exampleController{
def action1 = {getModel()}
def action2 = {getModel()}
def action3 = {getModel()}
def action4 = {getModel()}
def action5 = {getModel()}
private getModel() {
def user = session.user
[user: user]
}
}
While this does involve some amount of repetition (invocation of the same method), it's a lot more obvious what's happening here. When debugging/testing a controller it's easy to forget about filters and interceptors, which can often lead to questions like
what the #**% is going on here?
Use a filter - http://grails.org/doc/latest/guide/6.%20The%20Web%20Layer.html#6.6%20Filters - or an after interceptor - http://grails.org/doc/latest/guide/6.%20The%20Web%20Layer.html#6.1.5%20Controller%20Interceptors
I have a similar case, and I was modified the grails scaffolding for the controller's generator.
class MyClassController {
def list = {
...
}
def show = {
def eInstance = beanIfExist()
...
}
def edit = {
def eInstance = beanIfExist()
...
}
def update = {
def eInstance = beanIfExist()
...
}
def delete = {
def eInstance = beanIfExist()
...
}
def beanIfExist = {
def beanInstance = MyClass.get(params.id)
if (beanInstance) {
return beanInstance
} else {
flash.message = "Error, invalid record."
redirect(action: "list")
return null
}
}
}
It is my suggestion, now if do you need another that sent a data to view then you can use interceptors.

Resources