I'm new to grails and trying to get a list of Domain based on Embedded class's date field.
Below are Working fine
def res = User.findAll { lt 'createdDateTime', new Date }
def res = User.findAll { eq 'account.name', 'JOHN' }
But,
def res = User.findAll { lt 'account.createdDateTime', new Date }
the above always return empty list.
'Account' class is embedded into User class
User.groovy
class User {
String name
Integer age
Date ctratedDateTime // test
Account account
static embedded = [
'account'
]
}
Account.groovy
class Account {
String userName
String password
Date createdDateTime
}
def res = User.findAll {
account{
lt 'createdDateTime', new Date
}
}
For above getting the following error
org.codehaus.groovy.grails.web.servlet.mvc.exceptions.ControllerExecutionException: Executing action [list] of controller [com.test.UserController] caused exception: Runtime error executing action
at grails.plugin.cache.web.filter.PageFragmentCachingFilter.doFilter(PageFragmentCachingFilter.java:200)
at grails.plugin.cache.web.filter.AbstractFilter.doFilter(AbstractFilter.java:63)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.codehaus.groovy.grails.web.servlet.mvc.exceptions.ControllerExecutionException: Runtime error executing action
... 5 more
Caused by: java.lang.reflect.InvocationTargetException
... 5 more
Caused by: java.lang.NoSuchMethodError: com.test.UserController$_getFilteredForexRates_closure9.<init>(Ljava/lang/Object;Ljava/lang/Object;Lgroovy/lang/Reference;)V
at com.test.UserController$$EOqgV3Um.getFilteredForexRates(UserController.groovy:172)
at com.test.UserController$_closure5$$EOqgV3Um.doCall(UserController.groovy:109)
... 5 more
Am I doing in a correct way? Please suggest me the way to resolve.
Thanks.
you should use a nested closure:
def res = User.withCriteria{
account{
lt 'createdDateTime', new Date
}
}
Related
I'm trying to use ElasticSearch 1.0.0.2 in Grails 3.1.6.
The domain class is:
class Post {
String content
Date dateCreated
static belongsTo = [user: User]
static hasMany = [tags: Tag]
static searchable = {
tags component : true
user component: true
}
}
I've injected ElasticSearchService in my SearchController and trying to obtain search results as:
try {
def searchResult = elasticSearchService.search("${params.q}")
// def searchResult = Post.search("${params.q}")
println("search result: "+searchResult)
return [searchResult: searchResult]
}catch (e){
println e.message
return [searchError: true]
}
But getting error like this:
ERROR grails.plugins.elasticsearch.conversion.unmarshall.DomainClassUnmarshaller - Error unmarshalling property 'user' of Class Post with id 4
java.lang.IllegalStateException: Property Post.user is not mapped as [component], but broken search hit found.
at sun.reflect.GeneratedConstructorAccessor116.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at org.springsource.loaded.ri.ReflectiveInterceptor.jlrConstructorNewInstance(ReflectiveInterceptor.java:1075)
at org.codehaus.groovy.reflection.CachedConstructor.invoke(CachedConstructor.java:83)
at org.codehaus.groovy.reflection.CachedConstructor.doConstructorInvoke(CachedConstructor.java:77)
at org.codehaus.groovy.runtime.callsite.ConstructorSite$ConstructorSiteNoUnwrap.callConstructor(ConstructorSite.java:84)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:247)
at grails.plugins.elasticsearch.conversion.unmarshall.DomainClassUnmarshaller.unmarshallProperty(DomainClassUnmarshaller.groovy:206)
at sun.reflect.GeneratedMethodAccessor339.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1432)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:210)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:59)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:52)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:64)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:190)
Would someone please tell me what mistake i'm making. Thanks.
Had the same problem, used this piece from the elastisearch plugin documentation to change my component to references which fixed my problem:
3.8.1. Searchable Reference
The searchable-reference mapping mode is the default mode used for association, and requires the searchable class of the association to be root-mapped in order to have its own index. With this mode, the associated domains are not completely marshalled in the resulting JSON document: only the id and the type of the instances are kept. When the document is retrieved from the index, the plugin will automatically rebuild the association from the indices using the stored id.
Example
class MyDomain {
// odom is an association with the OtherDomain class, set as a reference
OtherDomain odom
static searchable = {
odom reference:true
}
}
// The OtherDomain definition, with default searchable
class OtherDomain {
static searchable = true
String field1 = "val1"
String field2 = "val2"
String field3 = "val3"
String field4 = "val4"
}
When indexing an instance of MyDomain, the resulting JSON documents will be sent to ElasticSearch:
{
"mydomain": {
"_id":1,
"odom": { "id":1 }
}
}
{
"otherdomain": {
"_id":1,
"field1":"val1",
"field2":"val2",
"field3":"val3",
"field4":"val4"
}
}
Here is the link to the documentation
http://noamt.github.io/elasticsearch-grails-plugin/docs/index.html#searchableComponentReference
I'm currently developing a grails application (Version 3.1.2) and I got a frustrating error that I currently cannot solve.
Lets have an example case:
// Domain classes
class RootBean {
NestedBean nestedBean
}
class NestedBean {
int nestedInteger
}
not much to say about it, its just an 1 to 1 relation with no back reference
Now lets specify my problem: I've got a create and an edit view which both render a editTemplate with all the possible inputs. With a new Object (create) everythings works fine but with a existing Object I want to update I get this GSP Error Message:
URI
/VMPMessung/edit/2
Class
groovy.lang.MissingPropertyException
Message
Request processing failed; nested exception is org.grails.gsp.GroovyPagesException: Error processing GroovyPageView: [views/rootBean/edit.gsp:13] Error executing tag <g:render>: [views/rootBean/_editTemplate.gsp:1] Error executing tag <g:form>: [views/rootBean/_editTemplate.gsp:150] Error executing tag <f:widget>: No such property: nestedInteger for class: RootBean
Caused by
No such property: nestedInteger for class: RootBean
The GSP Code:
<f:widget class="form-control"
property="nestedBean.nestedInteger"
bean="RootBean"/>
I also debugged through the Taglibary and discoverd that it's going wrong cause of the Type Integer, I got other String fields in the real object and they are working fine. The Error is thrown in the FormFieldsTagLib class at line 569
private CharSequence renderNumericInput(BeanPropertyAccessor propertyAccessor,Map model, Map attrs) {
if (!attrs.type && model.constraints?.inList) {
attrs.from = model.constraints.inList
if (!model.required) attrs.noSelection = ["": ""]
return g.select(attrs)
} else if (model.constraints?.range) {
attrs.type = attrs.type ?: "range"
attrs.min = model.constraints.range.from
attrs.max = model.constraints.range.to
} else {
attrs.type = attrs.type ?: getDefaultNumberType(model )
if (model.constraints?.scale != null) attrs.step = "0.${'0' * (model.constraints.scale - 1)}1"
if (model.constraints?.min != null) attrs.min = model.constraints.min
if (model.constraints?.max != null) attrs.max = model.constraints.max
}
if(propertyAccessor != null && attrs.value) {
attrs.value = g.fieldValue(bean: propertyAccessor.rootBean, field: propertyAccessor.propertyName)
// This call causes the Error
// Debugging Values: propertyAccessor.rootBean: RootBean,
// propertyAccessor.propertyName: nestedInteger
}
return g.field(attrs)
}
I guess they are trying to find the fieldName on the RootBean instead of the NestedBean but am I doing something wrong or is it a Bug on Grails side?
Hopefully some of you knows an answer to this, its really much a blocker for me :(
I am having the same issue, the weird thing is that in I am not having problem, I have it only in
I could fix it with a workaround, implementing in RootBean class a getter for nestedInteger:
def int getNumber() {
return nestedBean?.nestedInteger
}
That worked for me.
Could you solve it properly?
I am trying to write a Grails 3 interceptor that should check if certain variables are present in the HTTP Headers. If they are not present i would like to render a specific json view but it seems that the render method is not availble in the before() method.
boolean before() {
String header = request.getHeader("Authorization")
if(!header) {
BaseException exception = new BadRequestException("test")
render view: "/genericErrorReponse", model: [e: exception]
return false
}
Is there a better way to achieve the desired result?
I am getting the following error when trying to render the JSON view.
No qualifying bean of type [org.springframework.web.servlet.ViewResolver] is defined.
No qualifying bean of type [org.springframework.web.servlet.ViewResolver] is defined: expected single matching bean but found 4: groovyMarkupViewResolver,jsonViewResolver,beanNameViewResolver,mvcViewResolver. Stacktrace follows:
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.springframework.web.servlet.ViewResolver] is defined: expected single matching bean but found 4: groovyMarkupViewResolver,jsonViewResolver,beanNameViewResolver,mvcViewResolver
at grails.artefact.Interceptor$Trait$Helper.render(Interceptor.groovy:254) ~[grails-plugin-interceptors-3.1.1.jar:3.1.1]
at device.registration.RegistrationInterceptor.before(RegistrationInterceptor.groovy:13) ~[main/:na]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) ~[na:1.8.0_66]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) ~[na:1.8.0_66]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_66]
Interceptor Code
class RegistrationInterceptor {
boolean before() {
String header = request.getHeader("Authorization")
if(!header) {
render view: "/genericErrorResponse", model: [e: new BadRequestException()]
}
false
}
boolean after() { true }
void afterView() {
// no-op
}
}
JSON View [/genericErrorResponse]
model {
BaseException e
}
response.status e.status
json {
message e.message
error e.error
status e.status
timestamp e.timestamp
}
Stacktrace shows that you are trying to get a bean of type org.springframework.web.servlet.ViewResolver at RegistrationInterceptor.groovy:13. Grails has by default 4 different implementations for ViewResolver and you have to be specific which one do you want to use.
It seemed that it actually was a bug inside Grails 3. Please see https://github.com/grails/grails-core/issues/9688
Recently I upgraded grails from 1.3.4 to 2.2.2 and I'm getting following error while trying to iterate over a Set defined as hasMany in a domain.
class A {
String name
static hasMany = [bList: B]
}
class B {
static belongsTo = [a:A]
}
class TestController {
def test = {
A a = A.get(1L)
def bList = a.bList
bList.each{}
}
}
Above line bList.each {} is throwing following exception
java.lang.IllegalArgumentException: wrong number of arguments
at
org.grails.datastore.mapping.engine.event.AbstractPersistenceEventListener.onApplicationEvent(AbstractPersistenceEventListener.java:46)
at
com.test.TestController$_closure2.doCall(TestController.groovy:5)
at
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
at java.lang.Thread.run(Thread.java:680)
So I found the issue
Class B had a afterLoad() event hook attached to it which for some weird reason was throwing java.lang.IllegalArgumentException: wrong number of arguments exception I have now changed it to onLoad() Happy Days Now.
Thanks
Hussain
I assume that the issue involves the creation of the Groovy console inside the Grails instance; normal Domain object queries work fine, but attempting to query into a self-referential one-to-one causes issues.
I have a Domain class like the followng:
package demo
class Foo {
String name
static hasMany = [substitutes: Foo]
static constraints = {
}
}
During bootstrap, I create a Console to be able to inspect the domain objects:
import demo.Foo
import org.springframework.web.context.support.WebApplicationContextUtils
import org.codehaus.groovy.grails.commons.GrailsApplication
import grails.util.GrailsUtil
import groovy.ui.Console
class BootStrap {
def init = { servletContext ->
def one = new Foo([name: 'one'])
def two = new Foo([name: 'two'])
[one,two].each { it.save(failOnError: true, flush: true)}
one.addToSubstitutes(two)
one.save(failOnError: true, flush: true)
def appCtx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext)
def grailsApp = appCtx.getBean(GrailsApplication.APPLICATION_ID);
Binding b = new Binding();
b.setVariable("ctx", appCtx);
def console = new Console(grailsApp.classLoader, b);
console.run()
Foo.list().each{println it.name}
Foo.list().each{println it.substitutes}
println '--------------------------'
}
def destroy = {
}
}
This prints the following in the console:
one
two
[demo.Foo : 2]
null
--------------------------
Within the console, I attempt to repeat the two queries, which throws an exception:
groovy> import demo.Foo
groovy> demo.Foo.list().each{println it.name}
groovy> demo.Foo.list().each{println it.substitutes}
one
two
Exception thrown
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: demo.Foo.substitutes, no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:383)
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:375)
at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:368)
at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:111)
at org.hibernate.collection.PersistentSet.iterator(PersistentSet.java:186)
at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1243)
at ConsoleScript2$_run_closure2.doCall(ConsoleScript2:3)
at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1243)
at ConsoleScript2.run(ConsoleScript2:3)
at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1243)