Last updated by
10 months ago
Page: FAQ, Version:96
Frequently Asked Questions (FAQ)
#General- #Q: How can i use my grails services as a jar in some other java or spring project.
- #Q: I see something wrong! Can someone fix it? I want someone to enter in my additional FAQ or other information.
- #Q: After deployment as a WAR Grails becomes unresponsive when placed under load! What can I do?
- #Q: OMG I get OutOfMemoryErrors or PermGen Space errors when running Grails in development mode. What do I do?
- #Q: Grails won't run on my linux box! What's going on?
- #Q: I get an exception when loading my Grails application in my browser
- #Q: After I moved my domain classes to a package, they can not be resolved anymore
- #Q: How do I check my project into version control / I am getting strange SVN errors with files generated by Grails
- #Q: How do I report a bug, request a new feature, or suggest an improvement to the Grails documentation?
- #Q: Tomcat errors...
- #Q: I'm getting errors when deploying on JBoss 4.0.x What do I do?
- #Q: How do I setup Jetty behind Apache?
- #Q: How do I setup Grails on Oracle AS?
- #Q: Deploying on JETTY 6
- #Q: Deploying under IBM's J9 JVM (applies to WebSphere installs too)
- #Q: Deploying on Websphere
- #Q: WebSphere 6.1 tells me Error 404: SRVE0190E: File not found: /someController/someAction, what's happening?
- #Q: WebSphere 5.1 is giving me all sort of troubles, anyone got any luck with it ?
- #Q: I'd like to implement a big project as multi modules with Grails, What to do?
- #Q: When I point my browser at a particular page of my application, I get a 404 error that says <something>.jsp could not be found. I am using GSPs, so why is Grails looking for a JSP file that doesn't exist?
- #Q: Can I view my GSP's (Groovy Server Pages) directly?
- #Q: Why won't XXX Javascript Library Display Properly?
- #Q: What's the difference between fieldValue(bean:instance, field:"id") and instance.id?
- #Q: Can I use the render method to return a binary file to the client?
- #Q: How do I get the date from a form submission?
- #Q: Can I use JFreeChart to display charts to the client?
- #Q: In a one-to-many relationship, how to do I have a sorted set of the many objects?
- #Q: I have a simple domain class that gets errors when trying to view its list?
- #Q: How can I flush a Hibernate session multiple times within my controller?
- #Q: How can i use the new Groovy annotations for specifying JPA settings?
- #Q: How can I turn on logging for hibernate in order to see SQL statements, input parameters and output results?
- #Q: Why are my many-to-many columns backwards?
- #Q: How can I access domain classes from sources in src/groovy?
- #Q: How do I get access to the application context from sources in src/groovy?
- #Q: How do I get a resource from the servletContext or applicationContext from a service?
- #Q: Can Groovy work with Terracotta clustering cache?
- #Q: Do you need a GRAILS_HOME env variable? Is this issue maven related only?
- #Q: I see that the plugins directory is gone. Are there any other project structure differences we should know about?
- #Q: Migration: Since plugins now live in the ${user home}/.grails/plugins folder, should we delete the plugins folder, and then re-execute grails install-plugin xxx?
- #Q: Is the grails testing plugin part of the 1.1 dist?If so, do we still have to import grails.test.GrailsUnitTestCase?
- #Q: I think the join table mapping behavior has changed in 1.1, and there is a new mapping DSL syntax (is this true?). What are the ramifications and best practices for dealing with related issues?
- #Q: It seems many of the plugins may be broken now when trying to run in grails 1.1. What is the best way to follow up if we find an issue with a plugin, and where can we go to learn ahead of time if a plugin may have problems in 1.1?
General
Q: I see something wrong! Can someone fix it? I want someone to enter in my additional FAQ or other information.
Actually, anyone can do this! Just sign up for a Confluence account on Codehaus using the link from the login form after clicking on the pencil icon in the corner to edit the page. If you already have a Codehaus account, just sign in as you normally would.Q: After deployment as a WAR Grails becomes unresponsive when placed under load! What can I do?
The way Groovy's MetaClass system operates within Grails requires the Server VM. Grails cannot be deployed on the client VM and typically you need to assign more memory to the VM too. A good combination of settings to pass to the VM to run Grails is:-server -Xmx512M
Q: OMG I get OutOfMemoryErrors or PermGen Space errors when running Grails in development mode. What do I do?
Since Grails 0.6, Grails automatically re-compiles Java sources and domain classes using pre-compilation and then a server restart. This can lead to permgen space running out if the server is run for a long time and many changes are made. You can disable this feature if it is not important to you with:grails -Ddisable.auto.recompile=true run-appThere is also a problem with Grails 0.6 on Windows where you get OutOfMemoryErrors during a period of activity in development mode due to the re-compilation. This may be solved in SVN head, but if you see this problem the above option can also help.Q: Grails won't run on my linux box! What's going on?
It may be because you are using GNU java. Try running:java -version
sudo apt-get install sun-java6-jdk sudo update-alternatives --config java
Q: I get an exception when loading my Grails application in my browser
One thing to always check in case of unexpected exceptions is the value of the CLASSPATH variable in your console. Run {{set CLASSPATH}} on Windows and {{echo $CLASSPATH}} on Mac OS X, Linux and Unix to print the value. Grails does not depend on the CLASSPATH variable so in case it's set run {{set CLASSPATH=}} on Windows and {{export CLASSPATH=}} on Mac OS X, Linux and Unix to remove it.Q: After I moved my domain classes to a package, they can not be resolved anymore
Normally all Grails artefacts reside in the default package. Java disallows for classes in a (sub-)package to import classes from the default one, and so does Groovy.Try to move all your classes into packages and don't forget to import them.Q: How do I check my project into version control / I am getting strange SVN errors with files generated by Grails
Because Grails (certainly up to and including 0.4) generates and copies some files under the project tree, SVN and other version control systems can complain about files changing, or files not being in version control.For Subversion (SVN) the solution is to mark the correct directories or files to be "ignored". However how you do this is slightly obscure. See the article Checking Projects into SVN.Q: How do I report a bug, request a new feature, or suggest an improvement to the Grails documentation?
By opening an issue in the Grails issue tracking system. Grails development is managed by a JIRA installation hosted here: http://jira.codehaus.org/browse/GRAILS. You'll need to create an account on the JIRA system before you can create or comment on issues. Opening an issue is often referred to as "raising a JIRA" on the Grails mailing list. Note: it's generally a good idea to consult the Grails mailing list for help before raising a JIRA.Application Servers
Q: Tomcat errors...
Q: When deploying to my hosting ISP Tomcat, I'm getting an error along the lines of "org.springframework.beans.factory.BeanCreationException" or "org.hibernate.PropertyAccessException: IllegalArgumentException", originally caused by an "java.lang.IllegalArgumentException: object is not an instance of declaring class".
This is caused by a difference in timestamps between files inside your war file and your Tomcat server, and is triggered by timezone differences. After deploying the war, a simple:cd webapps find mygrailsappli -exec touch {} ;and restarting Tomcat will solve the problem. If you can't access the host via a login shell of some sort, then you'll probably need to change the timestamps on your WAR file to match your server before deploying it.Q: I drop the war file in the Tomcat webapps directory, and nothing happens. I see some Zip file errors in the log.
Try restarting Tomcat.Q: The war file unpacks okay in Tomcat, but then … nothing. I go to the URL and get a 404 error, no messages in the logs, no nothing.
Grails and Groovy have certain memory requirements.If memory is not a problem on your server then allocate a large amount of memory, such as 512m (512MB) or more. Also use the server VM option. EG: (-server -Xms512m -Xmx512m). Usually it is better to set both min and max heap size to the same in server applications. What this means is, edit your tomcat5.conf file, and set the option: JAVA_OPTS="-Xms512m -Xmx512m". The tomcat5.conf file is usually in CATALINA_HOME/conf, see the Tomcat website for more information. For more information on what the Java options mean, try calling java -X.However, if you running on a virtual host with limited memory, Grails 1.0 RC1 has been tested on tomcat 6 with both -Xmx96m and -Xmx128m, it performed well with both settings. I've heard reports of it running on lesser configurations. See: Grails Test On Virtual Server for more information.Also see http://grails.org/Deployment for more information.Q: I'm getting errors when deploying on JBoss 4.0.x What do I do?
JBoss' unified class loader can cause problems with conflicting Jar files. One issue commonly encountered is with log4j, which is part of both JBoss and Grails. This can be resolved by removing log4j.jar from your deployed .war file or using scoped classloading (with some caveats).Ideally you wouldn't want to remove the log4j file from your deployment as this requires some additional work and will break many automated deployment/testing processes. JBoss' class loaders are based on a hierarcy of classloaders but this causes issues where there are files shared between the JBoss parent classloaders and the child classloader for our web application. What we really want to do is tell JBoss to leave us alone when it comes across files that we have in our .war file. To do this we must 'scope' our classloader so that the classes we are using are in their own class loader repository away from the JBoss classes. To do this for a war is relatively straightforward. Create a file called jboss-web.xml and place it in your "web-app/WEB-INF" directory (it will be included in the WAR file's "WEB-INF"):<jboss-web> <class-loading java2ClassLoadingCompliance="false"> <loader-repository> myappname:loader=myappname.war <loader-repository-config>java2ParentDelegation=false</loader-repository-config> </loader-repository> </class-loading> </jboss-web>
"com.foocompany.webProjectBar:loader=webProjectFooBar.war"- Go in the servers conf directory. I have JBoss installed in /jboss-4.0.5.GA, so the conf directory is /jboss-4.0.5.GA/server/default/conf. If you are deploying into a profile other than default, simply substitute default for the name of the profile that you are deploying into such as /jboss-4.0.5.GA/server/foobarprofile/conf.
- Move the log4j.xml to jboss-log4j.xml
- Edit the jboss-service.xml file and find the mbean called "org.jboss.logging.Log4JService". Change the attribute "ConfigurationURL" so that it points to this new jboss-log4j.xml file:
<attribute name="ConfigurationURL">resource:jboss-log4j.xml</attribute>- Restart the JBoss application server and now any application that has log4j bundled in it will deploy properly and with their own log4j configuration.
<!-- ==================================================================== --> <!-- Log4j Initialization --> <!-- ==================================================================== --> <mbean code="org.jboss.logging.Log4jService" name="jboss.system:type=Log4jService,service=Logging" xmbean-dd="resource:xmdesc/Log4jService-xmbean.xml"> <attribute name="ConfigurationURL">resource:jboss-log4j.xml</attribute> <!-- Set the org.apache.log4j.helpers.LogLog.setQuiteMode. As of log4j1.2.8 this needs to be set to avoid a possible deadlock on exception at the appender level. See bug#696819. --> <attribute name="Log4jQuietMode">true</attribute> <!-- How frequently in seconds the ConfigurationURL is checked for changes --> <attribute name="RefreshPeriod">60</attribute> </mbean>
Q: How do I setup Jetty behind Apache?
Setting up Jetty behind apache is relatively straightforward. Jetty recommends that you utilize mod_proxy and proxy using http, not AJP.In your Apache install make sure mod_proxy and proxy_http are configured.Load the modules (normally in httpd.conf):LoadModule proxy_module /usr/lib/apache2/modules/mod_proxy.so
LoadModule proxy_http_module /usr/lib/apache2/modules/mod_proxy_http.so ProxyRequests Off <Proxy *>
Order deny,allow
Allow from .mydomain.com
</Proxy> ProxyPass /myapp http://mydomain.com:8080/myappLoadModule proxy_balancer_module /usr/lib/apache2/modules/mod_proxy_balancer.so ProxyRequests Off
ProxyPreserveHost On <Proxy *>
Order deny,allow
Allow from .mydomain.com
</Proxy> ProxyPass /myapp balancer://my_cluster/myapp stickysession=JSESSIONID nofailover=On <Proxy balancer://my_cluster>
BalancerMember http://yourJetty1:8080 route=jetty1
BalancerMember http://yourJetty2:8080 route=jetty2
</Proxy>Q: How do I setup Grails on Oracle AS?
There is a great tutorial on the Oracle website detailing exactly how to setup Grails on OracleQ: Deploying on JETTY 6
I had to remove the lib/jsp 2.1 directory from my jetty install to disable JSP 2.1Q: Deploying under IBM's J9 JVM (applies to WebSphere installs too)
WebSphere uses the J9 Java Virtual Machine. J9 is also one of the alternatives you'll have to consider on a PPC Linux box because the Sun JVM doesn't run there. Unfortunately J9 does a lot of work under the covers to make things run faster that don't work well with Groovy.Add '-Xverify:none' to JVM argumentsWithout this you'll get a NoClassDefFoundError.Under WebSphere you can set this via the WebSphere Administative Console: Application servers > server1 > Process Definition > Java Virtual Machine > Generic JVM arguments) save the change and restart the application server. (See also GRAILS-476.)Under Tomcat 5 you can add it to the tomcat5.confWe found that sending email caused j9 to throw a GPF Fault - and Tomcat then does it's version of a Core Dump. Perusing the dump file doesn't seem to help - as there is no indication of the class or method which caused GPF. GPF is short for General Protection Fault - which means that something is attempting to access a resource to which they do not have permission (per the underlying operating system). And finally once past the GPF mail wouldn't send due to some incompatiblity with the Gnu JavaMail API and the Sun specification JavaMail API. Once the Gnu mail.jar was replaced with the Sun version - email functioned normally.Q: Deploying on Websphere
- Also read Deployment to WebSphere
Caused by: org.apache.commons.logging.LogConfigurationException: The chosen LogFactory implementation does not extend LogFactory. Please check your configuration...
- Delete commons-logging-1.1.jar from the lib directory
<filter>
<filter-name>filterChainProxy</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>Q: WebSphere 6.1 tells me Error 404: SRVE0190E: File not found: /someController/someAction, what's happening?
It seems to be related to a bug in WebSphere that doesn't handle servlet filters properly. As seen in the Jive support forums, setting the com.ibm.ws.webcontainer.invokefilterscompatibility property to true in Servers > Server > Web Container Settings > Web Container > Custom Properties, may help solve the issue.Q: WebSphere 5.1 is giving me all sort of troubles, anyone got any luck with it ?
There isn't a crystal-clear procedure for WebSphere 5.1 deployment of grails 1.0.X applications yet. Some of the solutions detailed above are applicable to WebSphere 5.1, but some are relevant to 6.X only.For more information on a person's own difficulties with this, see Deploying to WebSphere 5.x Journal. Please consider contributing to that page if you make progress on it or if you know the steps for a successful deployment.Q: I'd like to implement a big project as multi modules with Grails, What to do?
Since version 0.4, Grails has came with a plugin architecture. You can separate your project as a set of plugins. See how to develop a plug-in here.View Technologies
Q: When I point my browser at a particular page of my application, I get a 404 error that says <something>.jsp could not be found. I am using GSPs, so why is Grails looking for a JSP file that doesn't exist?
When you get this error, Grails has already looked for the appropriate GSP file but not found it. It then looks for a suitable JSP file and if that can not be found, you get the error about the JSP file. So if you are using GSPs and see this error, you need to check that the GSP file is in the right place with the correct name.Q: Can I view my GSP's (Groovy Server Pages) directly?
A: Yes, GSPs in the 'views' directory are directly accessible. You can prevent direct access to the GSPs by intercepting "/**.gsp" in UrlMappings.groovyQ: Why won't XXX Javascript Library Display Properly?
A: Sometimes third party javascript libraries depend upon other resources loaded directly from the javascript files themselves like stylesheets. Examples of libraries that do this would be the Yahoo UI libraries and niftycube. When the javascript attempts to load the URL Grails changes the URL so that the resource is not found. Try adding a link using the createLinkTo tag for the particular resource.Q: What's the difference between fieldValue(bean:instance, field:"id") and instance.id?
A: Per Ian Roberts(i.roberts@dcs.shef.ac.uk) on grails user mailing list 5/16/11 -- The difference betweenrequestInstance.attr
fieldValue(bean:requestInstance, field:'attr')
Controllers
Q: Can I use the render method to return a binary file to the client?
A: Not at the moment. However the servlet response instance can be used. For example, a zip file is created on the server and returned to the client:def createZip = {
byte[] zip = createZipForClient()
response.contentType = "application/octet-stream"
response.outputStream << zip
}Alternatively, you can use:
response.setHeader("Content-disposition", "attachment; filename=" + session.userid + ".csv"); render(contentType: "text/csv", text: "my,comma,seperated,variable,file");
Q: How do I get the date from a form submission?
The actual date parameter that is the same as your class (in the sample below, "startDate") is simply a tag that tells grails that it is a struct. To get at the actual date input by the user, you need to look at the individual month, year & day parameters.String inputDateString = "${params.startDate_year}/${params.startDate_month}/${params.startDate_day}" Date inputDate = new SimpleDateFormat("yyyy/MM/dd").parse(inputDateString)
Q: Can I use JFreeChart to display charts to the client?
Of course you can! Just use JFreeChart to create an image of the chart you want to show and then stream that back through the response.An example of a controller that creates a Pie Chart:import org.jfree.chart.ChartFactory import org.jfree.data.general.DefaultPieDataset import org.jfree.chart.encoders.EncoderUtilclass PiechartController { def index = { // create the data for the pie chart def slices = [ [label:"One", percent:43.2], [label:"Two", percent:10.0], [label:"Three", percent:27.5], [label:"Four", percent:17.5], [label:"Five", percent:11.0], [label:"Six", percent:19.4] ] // load the data into a dataset def dataset = new DefaultPieDataset(); slices.each { slice -> dataset.setValue(slice.label, slice.percent) } // create the pie chart and stream it back to the client def chart = ChartFactory.createPieChart("Pie Chart Demo 1", dataset, true, true, false) EncoderUtil.writeBufferedImage(chart.createBufferedImage(800, 600), "png", response.getOutputStream()) }}
You will also need to copy jfreechart-1.0.1.jar and jcommon-1.0.0.jar into the libs folder of your grails app.
Grails Object Relational Mapping (GORM)
Q: In a one-to-many relationship, how to do I have a sorted set of the many objects?
In the Author/Book example, Book must implement the Comparable interface, and the set of books must be of type SortedSet:class Author {
Long id
Long version
SortedSet books def hasMany = [ books : Book ] String name
}See also Section 5.2.4 of the GORM documentation.
Q: I have a simple domain class that gets errors when trying to view its list?
Be careful with SQL reserved words. The code bellow will result in mapping errors because "order" is an SQL reserved word. Change that to "sortOrder" or something else.class Category{
String name
Integer order
}Q: How can I flush a Hibernate session multiple times within my controller?
Spring will inject the a SessionFactory object into your controller, provided you import the proper libraries and provide a reference for the injection:import org.hibernate.*class SomeController { SessionFactory sessionFactory def flush_multiple_times = { assert sessionFactory != null def hibSession = sessionFactory.getCurrentSession() assert hibSession != null hibSession.flush() // do something hibSession.flush() } }
Q: How can i use the new Groovy annotations for specifying JPA settings?
The Grails DomainBinder does not use the annotations, so you have to put the Domain class in the src/groovy folder (instead of grails-app/domain).- Create your domain-class in src/groovy, e.g. src/groovy/Book.groovy :
import javax.persistence.*;@Entity class Book { @Id @GeneratedValue(strategy = GenerationType.AUTO) @SequenceGenerator(name="book_seq", sequenceName="book_seq") Long id; @Version Integer version; @Column(name="my_auth_col") String author; @Column(name="my_title_col") String title; static constraints = { author(nullable:true) title(nullable:true) } }
- Configure annotation support in your xxxDataSource.groovy :
import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsAnnotationConfiguration
class DevelopmentDataSource {
def configClass = GrailsAnnotationConfiguration.class
...- Register your domain class in hibernate/hibernate.cfg.xml, e.g. :
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><hibernate-configuration> <session-factory> <mapping class="Book" /> </session-factory></hibernate-configuration>
- grails generate-all Book, and of you go !
Q: How can I turn on logging for hibernate in order to see SQL statements, input parameters and output results?
Edit your Config.groovy file. Find the line with:
hibernate = "off"and replace it with:
hibernate.SQL="trace,stdout" hibernate.type="trace,stdout"
now you will see SQL logging statements appear on the console.
Q: Why are my many-to-many columns backwards?
This is intentional - see this JIRA for an explanation of what's going on. See this JIRA for a proposed fix.Security
Q: How can I secure my application?
There are a number of ways to secure your application, a simple way is with a Grails filter.However, it is recommended that you build your application on one of the excellent security plug-ins for Grails such as the Spring Security 2.0 plug-in or the JSecurity plug-in both which solve a lot of common security patterns (login, registration, roles, permissions etc.)Grails in Eclipse
Q: Launching Grails in Eclipse fails with an exception about JAVA_HOME
Your Eclipse is configured to use a Java Runtime Environment or JRE. However, to launch a Grails application you need a Java Developer Kit or JDK. If you don't have a JDK installed on your system your can download the latest version from http://java.sun.comGo to Preference in Eclipse (in the Window menu) and go to "Java/Installed JREs". You will find a JRE installed, for example "jre1.5.0_09". Now add the JDK by clicking the "Add..." button. Click the "Browse..." button and select the location of your JDK (for example "C:Program FilesJavajdk1.5.0_09"). Click "Ok" and enter a name for this JDK (for example "JDK 1.5.0_09").Now make sure to select the JDK you just installed in your launch configuration.Misc
Q: How can I access domain classes from sources in src/groovy?
Sometimes, you are developing some utility classes that live in src/groovy and which you intend to use from Services and other artifacts. However, as those classes are pre-compiled by Grails, it is not possible to instantiate them and write things like Book.findByTitle("Groovy in Action"). But fortunately, there is a workaround since it's possible to do this:import org.codehaus.groovy.grails.commons.ApplicationHolder //… def book = ApplicationHolder.application.getClassForName("library.Book").findByTitle("Groovy in Action")
Q: How do I get access to the application context from sources in src/groovy?
There is no ApplicationContextHolder class equivalent to ApplicationHolder. To access to a service class called EmailService from a Groovy class in src/groovy, access the Spring bean using:import org.codehaus.groovy.grails.web.context.ServletContextHolder as SCH import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes as GAdef ctx = SCH.servletContext.getAttribute(GA.APPLICATION_CONTEXT) def emailService = ctx.emailService
import org.codehaus.groovy.grails.commons.ApplicationHolder as AH
def ctx = AH.application.mainContext
def emailService = ctx.emailServiceQ: How do I get a resource from the servletContext or applicationContext from a service?
To get the ApplicationContext, have your service implement ApplicationContextAware and declare an 'applicationContext' field. Then from within your service:def resource = applicationContext.getResource("foo")import org.codehaus.groovy.grails.web.context.ServletContextHolder as SCHdef servletContext = SCH.servletContext