Criteria in grails - grails

Could you tell me what's wrong in my Criteria here?
def users
def u = User.createCriteria()
users = u.list (max: max, offset: offset) {
eq("account",account)
and {
if(teacherName != null && teacherName != ""){
like("userName", "%"+teacherName+"%")
}
if(mobileNumber != null && mobileNumber != ""){
like("mobileNumber", "%"+mobileNumber+"%")
}
eq("status", Status.ACTIVE)
eq("userType","Account Teacher")
}
}
return users
}
the list returned empty why?

The code you posted is unnecessarily verbose. An equivalent implementation is:
def users = User.withCriteria(max: max, offset: offset) {
eq("account", account)
if (teacherName) {
like("userName", "%${teacherName}%")
}
if (mobileNumber) {
like("mobileNumber", "%${mobileNumber}%")
}
eq("status", Status.ACTIVE)
eq("userType", "Account Teacher")
}
I can't say why this isn't working because I don't know what the User domain class looks like or what behaviour the query is supposed to exhibit, but it ought to be easier to debug a more concise implementation.

Related

How to get the value from sum() in a Grails criteria

I can't use the + operator with resultado[0] + obj.nopersonas, nopersonas is an Integer.
fhinicio(blank:false, validator : { val, obj ->
def diff = groovy.time.TimeCategory.minus(obj.fhfinal, val)
def total = diff.hours*60 + diff.minutes
if (total < 15){
return "reserva.fhfinal.tiempo.min.label"
} else {
if (total > 60) {
return "reserva.fhfinal.tiempo.max.label"
} else {
def reserva = Reserva.createCriteria()
def resultado = reserva.list() {
or {
and {
ge('fhinicio', val)
le('fhinicio', obj.fhfinal)
}
and {
ge('fhfinal', val)
le('fhfinal', obj.fhfinal)
}
}
projections {
sum('nopersonas')
}
}
//this is not working
def aff = resultado[0] + obj.nopersonas
Cannot execute null+null. Stacktrace follows: Message: Cannot execute null+null
You've got a couple of problems to resolve:
The criteria query is returning null
obj.nopersonas is null
The criteria query
To fix the criteria query, start without the projection:
def reserva = Reserva.createCriteria()
def resultado = reserva.list {
or {
and {
ge('fhinicio', val)
le('fhinicio', obj.fhfinal)
}
and {
ge('fhfinal', val)
le('fhfinal', obj.fhfinal)
}
}
}
Make sure you're getting the appropriate instances of Reserva. Then, add the projection and since you're expecting a single value, use the get() method instead of list().
def reserva = Reserva.createCriteria()
def resultado = reserva.get {
or {
and {
ge('fhinicio', val)
le('fhinicio', obj.fhfinal)
}
and {
ge('fhfinal', val)
le('fhfinal', obj.fhfinal)
}
}
projections {
sum('nopersonas')
}
}
def aff = resultado + obj.nopersonas
obj.nopersonas
Since obj.nopersonas is null, I'm assuming the property is nullable. If the property is supposed to be nullable, then you'll need to account for that in your validator.
It is working.
Integer variable_name = Integer.valueOf(resultado[0].toString())
You can simply handle the null condition:
def aff = (resultado[0] ?: 0) + (obj.nopersonas ?: 0)

Including the max and offset criteria inside GORM criteriaBuilder returns an error

Can I make this code shorter?
if(count == null && from = null) {
creditAdviceList = CreditAdvice.findAll {
ilike('id', "%$idFilter%")
.....
ilike('statusCode', statusCodeFilter)
}
}
else if(count != null && from == null) {
creditAdviceList = CreditAdvice.findAll(max: count) {
ilike('id', "%$idFilter%")
.....
ilike('statusCode', statusCodeFilter)
}
}
else if(count == null && from != null) {
creditAdviceList = CreditAdvice.findAll(offset: from) {
ilike('id', "%$idFilter%")
.....
ilike('statusCode', statusCodeFilter)
}
}
else if(count != null && from != null) {
creditAdviceList = CreditAdvice.findAll(max: count, offset: from) {
ilike('id', "%$idFilter%")
.....
ilike('statusCode', statusCodeFilter)
}
}
You see, its a series if statement for each possible scenario. Imagine if one would to use also order and cache in the parameter- there will be basically 16 unique if statements!
I've tried this [more] shorter code:
creditAdviceList = CreditAdvice.findAll {
ilike('id', "%$idFilter%")
.....
ilike('statusCode', statusCodeFilter)
if(count != null) {
maxResults(count)
}
if(from != null) {
firstResult(from)
}
}
But it gives me an error:
...No signature of method: grails.gorm.DetachedCriteria.maxResults() is applicable for argument types: (java.lang.Integer)...
I tried to convert offset to int, Integer, String, etc. I also omit the if statement inside the criteria, but the same error message occur.
findAll with a closure passed is using a DetachedCriteria internally, which is not the same as the result you would get from createCriteria mentioned in the docs. If groovy would find "something close" enough, it would tell you in the error message. The easiest way to deal with your max/from demands would be with simply with a map (which is the first argument passed). E.g.:
def qcfg = [:]
if (count) {
qcfg.count = count
}
if (from) {
qcfg.offset = from
}
creditAdviceList = CreditAdvice.findAll(qcfg) { ... }
mix, match, extract, shorten as you see fit
As far as I see, the only difference is the pagination options. If my eyes are not tricking me, yes, you can:
Map paginationArgs = [max: count, offset: from].findAll {
it.value != null
}
List<CreditAdvice> creditAdviceList = CreditAdvice.findAll(paginationArgs) {
ilike('id', "%$idFilter%")
.....
ilike('statusCode', statusCodeFilter)
}
You can style it differently, but basically you can build the pagination arguments first, and pass them to the findAll. No duplicated code, clearer responsability of the conditions. To clarify, I'm adding all the options and then filtering them to exclude the ones that are null.

Redirect to external site does not terminate current execution flow

I'm using grails 1.3.7.
I have the following filter setup:
class MyFilters {
def userService
def springSecurityService
def filters = {
all(controller: '*', action: '*') {
before = {
String userAgent = request.getHeader('User-Agent')
int buildVersion = 0
// Match "app-/{version}" where {version} is the build number
def matcher = userAgent =~ "(?i)app(?:-\\w+)?\\/(\\d+)"
if (matcher.getCount() > 0)
{
buildVersion = Integer.parseInt(matcher[0][1])
log.info("User agent is from a mobile with build version = " + buildVersion)
log.info("User agent = " + userAgent)
String redirectUrl = "https://anotherdomain.com"
if (buildVersion > 12)
{
if (request.queryString != null)
{
log.info("Redirecting request to anotherdomain with query string")
redirect(url:"${redirectUrl}${request.forwardURI}?${request.queryString}",params:params)
}
return
}
}
}
after = { model ->
if (model) {
model['currentUser'] = userService.currentUser
}
}
afterView = {
}
}
}
}
A problem occurs in that the redirect does not happen at the point I would have thought.
I want all execution to stop and redirect to the exaact url I have given it at this point.
When i debug to the "redirect" line, it continues past this line exectuting other lines and jumping to another controller.
In order to prevent the normal processing flow from continuing, you need to return false from your before filter:
if (buildVersion > 12)
{
if (request.queryString != null)
{
log.info("Redirecting request to anotherdomain with query string")
redirect(url:"${redirectUrl}${request.forwardURI}?${request.queryString}",params:params)
return false
}
}
This is mentioned in passing at the very end of section 6.6.2 of the user guide, but it isn't particularly prominent:
Note how returning false ensure that the action itself is not executed.

Criteria building in GORM

if (params.filters) {
def o = JSON.parse(params.filters);
def groupOp = o.groupOp
def fields = o.rules.field
def values = o.rules.data
def op = o.rules.op
println fields
println values
if(groupOp == "AND") {
fields.eachWithIndex {a, i ->
println op[i]
if(op[i].equals( "eq")) {
and{ eq(fields[i], values[i])}
}
if(op[i].equals("ne")) {
and{ ne(fields[i], values[i])}
}
if(op[i].equals("ge")) {
def valu = Double.valueOf( values[i]);
and{ ge(fields[i], valu)}
}
}
}
if(groupOp == "OR") {
fields.eachWithIndex {a, i ->
println op[i]
if(op[i].equals( "eq")) {
println 'eq';
or{ eq(fields[i], values[i])}
}
if(op[i].equals("ne")) {
println 'ne';
or{ ne(fields[i], values[i])}
}
if(op[i].equals("ge")) {
def valu = Double.valueOf( values[i]);
or{ ge(fields[i], valu)}
}
}
}
}
where params.filters is following JSON text.
{
"groupOp":"OR",
"rules":[
{
"field":"foo1",
"op":"le",
"data":"9.5"
},
{
"field":"foo2",
"op":"eq",
"data":"12345-123"
},
{
"field":"foo3",
"op":"cn",
"data":"IDM"
}
]
}
This data is coming from JQuery data grid.
Is there a better way of doing this?
In the code I have just listed only 3 operators, but in real I have 14 operations.
You can use String as Criteria operation, like:
A.withCriteria {
'eq' (id, 1)
}
so you might come to something like
A.withCriteria {
(groupOp) {
for (???) {
(op[i]) (fields[i], parsedVals[i])
}
}
}
Anyway you'll need to sanitize the web-submitted query for only allowed subset of operations. You don't want to receive end execute arbitrary sqlRestriction, right? :D So the code is going to be more complex then this anyway.
Note: wrapping and{} or or {} around single statement has no point, you need to put it around whole block of if-s.
I suggest that you have a look at the source code of the FilterPane plugin. Its service does essentially what you are doing and may give you some ideas for enhancements.

removeFrom* not working and with no errors

I have what I think is a simple problem but have been unable to solve...
For some reason I have a controller that uses removeFrom*.save() which throws no errors but does not do anything.
Running
Grails 1.2
Linux/Ubuntu
The following application is stripped down to reproduce the problem...
I have two domain objects via create-domain-class
- Job (which has many notes)
- Note (which belongs to Job)
I have 3 controllers via create-controller
- JobController (running scaffold)
- NoteController (running scaffold)
- JSONNoteController
JSONNoteController has one primary method deleteItem which aims to remove/delete a note.
It does the following
some request validation
removes the note from the job - jobInstance.removeFromNotes(noteInstance).save()
deletes the note - noteInstance.delete()
return a status and remaining data set as a json response.
When I run this request - I get no errors but it appears that jobInstance.removeFromNotes(noteInstance).save() does nothing and does not throw any exception etc.
How can I track down why??
I've attached a sample application that adds some data via BootStrap.groovy.
Just run it - you can view the data via the default scaffold views.
If you run linux, from a command line you can run the following
GET "http://localhost:8080/gespm/JSONNote/deleteItem?job.id=1&note.id=2"
You can run it over and over again and nothing different happens. You could also paste the URL into your webbrowser if you're running windows.
Please help - I'm stuck!!!
Code is here link text
Note Domain
package beachit
class Note
{
Date dateCreated
Date lastUpdated
String note
static belongsTo = Job
static constraints =
{
}
String toString()
{
return note
}
}
Job Domain
package beachit
class Job
{
Date dateCreated
Date lastUpdated
Date createDate
Date startDate
Date completionDate
List notes
static hasMany = [notes : Note]
static constraints =
{
}
String toString()
{
return createDate.toString() + " " + startDate.toString();
}
}
JSONNoteController
package beachit
import grails.converters.*
import java.text.*
class JSONNoteController
{
def test = { render "foobar test" }
def index = { redirect(action:listAll,params:params) }
// the delete, save and update actions only accept POST requests
//static allowedMethods = [delete:'POST', save:'POST', update:'POST']
def getListService =
{
def message
def status
def all = Note.list()
return all
}
def getListByJobService(jobId)
{
def message
def status
def jobInstance = Job.get(jobId)
def all
if(jobInstance)
{
all = jobInstance.notes
}
else
{
log.debug("getListByJobService job not found for jobId " + jobId)
}
return all
}
def listAll =
{
def message
def status
def listView
listView = getListService()
message = "Done"
status = 0
def response = ['message': message, 'status':status, 'list': listView]
render response as JSON
}
def deleteItem =
{
def jobInstance
def noteInstance
def message
def status
def jobId = 0
def noteId = 0
def instance
def listView
def response
try
{
jobId = Integer.parseInt(params.job?.id)
}
catch (NumberFormatException ex)
{
log.debug("deleteItem error in jobId " + params.job?.id)
log.debug(ex.getMessage())
}
if (jobId && jobId > 0 )
{
jobInstance = Job.get(jobId)
if(jobInstance)
{
if (jobInstance.notes)
{
try
{
noteId = Integer.parseInt(params.note?.id)
}
catch (NumberFormatException ex)
{
log.debug("deleteItem error in noteId " + params.note?.id)
log.debug(ex.getMessage())
}
log.debug("note id =" + params.note.id)
if (noteId && noteId > 0 )
{
noteInstance = Note.get(noteId)
if (noteInstance)
{
try
{
jobInstance.removeFromNotes(noteInstance).save()
noteInstance.delete()
message = "note ${noteId} deleted"
status = 0
}
catch(org.springframework.dao.DataIntegrityViolationException e)
{
message = "Note ${noteId} could not be deleted - references to it exist"
status = 1
}
/*
catch(Exception e)
{
message = "Some New Error!!!"
status = 10
}
*/
}
else
{
message = "Note not found with id ${noteId}"
status = 2
}
}
else
{
message = "Couldn't recognise Note id : ${params.note?.id}"
status = 3
}
}
else
{
message = "No Notes found for Job : ${jobId}"
status = 4
}
}
else
{
message = "Job not found with id ${jobId}"
status = 5
}
listView = getListByJobService(jobId)
} // if (jobId)
else
{
message = "Couldn't recognise Job id : ${params.job?.id}"
status = 6
}
response = ['message': message, 'status':status, 'list' : listView]
render response as JSON
} // deleteNote
}
I got it working... though I cannot explain why.
I replaced the following line in deleteItem
noteInstance = Note.get(noteId)
with the following
noteInstance = jobInstance.notes.find { it.id == noteId }
For some reason the jobInstance.removeFromNotes works with the object returned by that method instead of .get
What makes it stranger is that all other gorm functions (not sure about the dynamic ones actually) work against the noteInstance.get(noteId) method.
At least it's working though!!
See this thread: http://grails.1312388.n4.nabble.com/GORM-doesn-t-inject-hashCode-and-equals-td1370512.html
I would recommend using a base class for your domain objects like this:
abstract class BaseDomain {
#Override
boolean equals(o) {
if(this.is(o)) return true
if(o == null) return false
// hibernate creates dynamic subclasses, so
// checking o.class == class would fail most of the time
if(!o.getClass().isAssignableFrom(getClass()) &&
!getClass().isAssignableFrom(o.getClass())) return false
if(ident() != null) {
ident() == o.ident()
} else {
false
}
}
#Override
int hashCode() {
ident()?.hashCode() ?: 0
}
}
That way, any two objects with the same non-null database id will be considered equal.
I just had this same issue come up. The removeFrom function succeeded, the save succeeded but the physical record in the database wasn't deleted. Here's what worked for me:
class BasicProfile {
static hasMany = [
post:Post
]
}
class Post {
static belongsTo = [basicProfile:BasicProfile]
}
class BasicProfileController {
...
def someFunction
...
BasicProfile profile = BasicProfile.findByUser(user)
Post post = profile.post?.find{it.postType == command.postType && it.postStatus == command.postStatus}
if (post) {
profile.removeFromPost(post)
post.delete()
}
profile.save()
}
So it was the combination of the removeFrom, followed by a delete on the associated domain, and then a save on the domain object.

Resources