Code Examples


Video 16: Simple Security

File: EndUser.groovy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package projecttracker

class EndUser {
    String userName
    String password
    String fullName
    String toString() {
        "${fullName}"
    }

    static constraints = {
        fullName()     
        userName(unique: true)
        password(password: true)
       
    }
    static hasMany = [projects : Project, tasks : Task]
}

File: login.gsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<%@ page import="projecttracker.EndUser" %>
<!doctype html>
<html>
    <head>
        <meta name="layout" content="main">
        <g:set var="entityName" value="ProjectTracker Login" />
        <title><g:message code="ProjectTracker Login" args="[entityName]" /></title>
    </head>
    <body>
        <a href="#create-endUser" class="skip" tabindex="-1"><g:message code="default.link.skip.label" default="Skip to content&hellip;"/></a>
        <div class="nav" role="navigation">
            <ul>
                <li><a class="home" href="${createLink(uri: '/')}"><g:message code="default.home.label"/></a></li>
                <li><g:link class="list" action="logout"><g:message code="Logout" args="[entityName]" /></g:link></li>
            </ul>
        </div>
        <div id="create-endUser" class="content scaffold-create" role="main">
            <h1><g:message code="ProjectTracker Login" /></h1>
            <g:if test="${flash.message}">
            <div class="message" role="status">${flash.message}</div>
            </g:if>
            <g:hasErrors bean="${endUserInstance}">
            <ul class="errors" role="alert">
                <g:eachError bean="${endUserInstance}" var="error">
                <li <g:if test="${error in org.springframework.validation.FieldError}">data-field-id="${error.field}"</g:if>><g:message error="${error}"/></li>
                </g:eachError>
            </ul>
            </g:hasErrors>
            <g:form action="authenticate" >
                <fieldset class="form">
                    <div class="fieldcontain ${hasErrors(bean: endUserInstance, field: 'userName', 'error')} ">
                        <label for="userName">
                            <g:message code="endUser.userName.label" default="User Name" />
                           
                        </label>
                        <g:textField name="userName" value="${endUserInstance?.userName}"/>
                    </div>
                   
                    <div class="fieldcontain ${hasErrors(bean: endUserInstance, field: 'password', 'error')} ">
                        <label for="password">
                            <g:message code="endUser.password.label" default="Password" />
                           
                        </label>
                        <g:field type="password" name="password" value="${endUserInstance?.password}"/>
                    </div>
                </fieldset>
                <fieldset class="buttons">
                    <g:submitButton name="login" class="save" value="Login" />
                </fieldset>
            </g:form>
        </div>
    </body>
</html>

File: EndUserController.groovy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def login = {}
   
    def authenticate = {
        def user = EndUser.findByUserNameAndPassword(params.userName, params.password)
        if(user){
            session.user = user
            flash.message = "Hello ${user.fullName}!"
            redirect(action:"login")
           
        }else{
        flash.message = "Sorry, ${params.userName}. Please try again."
        redirect(action:"login")
        }
    }
   
    def logout = {
        flash.message = "Goodbye ${session.user.fullName}"
        session.user = null
        redirect(action:"login")
    }

File: ProjectController.groovy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package projecttracker

class ProjectController {

    def beforeInterceptor = [action:this.&auth]
   
    def scaffold=true
    def index() {
        redirect(action: "list")
    }
    def auth() {
        if(!session.user) {
            redirect(controller:"EndUser", action:"login")
            return false
        }
    }
   
}

Video 15: Constraints and Static Scaffolding

File: Project.groovy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package projecttracker

class Project {
    String name
    String description
    Date dueDate
    String billingType
    String toString () {
        "${name}"
    }
    static belongsTo = [owner : EndUser]
    static hasMany = [tasks : Task]

    static constraints = {
        name(blank: false, unique: true)
        description()
        dueDate(min: new Date())
        billingType(inList: ["Hourly", "Milestone", "Non-billable"])
    }
}

Video 13: Designing the Data Model

File: Project.groovy

1
2
3
4
5
6
7
8
9
10
11
12
package projecttracker

class Project {
    String name
    String description
    Date dueDate
    static belongsTo = [owner : EndUser]
    static hasMany = [tasks : Task]

    static constraints = {
    }
}

File: Task.groovy

1
2
3
4
5
6
7
8
9
10
11
12
package projecttracker

import java.util.Date;

class Task {
    String name
    String description
    Date dueDate
    static belongsTo = [assignee : EndUser, project : Project]
    static constraints = {
    }
}

File: EndUser.groovy

1
2
3
4
5
6
7
8
9
10
11
package projecttracker

class EndUser {
    String userName
    String password
    String fullName
    static hasMany = [projects : Project, tasks : Task]

    static constraints = {
    }
}

Videos 11-12: Creating a Model

File: ListProjects.groovy

1
2
3
4
5
6
7
8
9
10
package projecttracker

class ListProjects {
    String name
    String description
    Date dueDate

    static constraints = {
    }
}

File: ListProjectsController.groovy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package projecttracker

class ListProjectsController {

    def index = {
        redirect (action: current)
    }
   
    def current = {
        def allProjects = ListProjects.list()
        [allProjects:allProjects]
    }
   
    def overdue = {
        render "Order Valentines Day Package"
    }
}

File: current.gsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<html>
<head>
   <title>Current Projects</title>
</head>

<body>
<table border="1">
    <g:each in="${allProjects}" status="i" var="thisProject">
        <tr>
            <td>${thisProject.name}</td>
            <td>${thisProject.description}</td>
            <td>${thisProject.dueDate}</td>
        </tr>
    </g:each>
</table>
</body>
</html>

Video 10: Creating a View

File: ListProjectsController.groovy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package projecttracker

class ListProjectsController {
    def index = {
        redirect (action:current)
    }

    def current = {
        def projectName = "Project Tracker Video Tutorials"
        def dueDate = "3/3/2012"
        [project:projectName, date:dueDate]
    }

    def overdue = {
        render "Order Valentines Day Package"
    }

File: current.gsp

1
2
3
4
5
6
7
8
9
10
11
<html>
<head>
   <title>Current Projects</title>
</head>
<body>
   <form>
      Project: <input type="text" size=40 name="project" value=${project}" />
      <p>Due Date: <input type="text" name="date" value=${date}" /></p>
   </form>
</body>
</html>

Video 9: Creating a Controller

File: ListProjectsController.groovy

1
2
3
4
5
6
7
8
9
10
11
12
class ListProjectsController {
    def index = {
        redirect (action: current)
    }

    def current = {
        render "Project Tracker Video Tutorials"
    }

    def overdue = {
        render "Order Valentines Day Package"
    }

34 thoughts on “Code Examples

  1. Hi,

    Me and my teammates are new to grails and we are trying to query the dates of a certain event which are 2 weeks in advance from the current date. I tried the findAll method, but it didn’t work. We are connecting to a postgresql database.

  2. Hi, thanks for those wonderful and really helpful tutorials..
    I learned a lot about making an application in grails

    can you help me with this:
    how to implement a time field in grails domain class?

    I tried Joda Time, but it didn’t work…
    maybe I just don’t know how to use Joda Time in my application

    • Hi. Not sure if this will help, but I have been working with the GregorianCalendar() library to manipulate date and time fields in my applications, then making them look nice with the format() library.

      • sir, really thank you for your reply, hope I’m not annoying you, but can you help us again with our next problem and that is passing data from the controller to …. Actually we would like a certain data from our controller to be passed inside google.visualization.arrayToDataTable() and replace the values that are being defined inside it.

        google.load(“visualization”, “1″, {packages:["corechart"]});
        google.setOnLoadCallback(drawChart);
        function drawChart() {
        var data = google.visualization.arrayToDataTable([
        ['Year', 'Sales', 'Expenses'],
        ['2004', 1000, 400],
        ['2005', 1170, 460],
        ['2006', 660, 1120],
        ['2007', 1030, 540]
        ]);

        var options = {
        title: ‘Company Performance’,
        hAxis: {title: ‘Year’, titleTextStyle: {color: ‘red’}}
        };

        var chart = new google.visualization.ColumnChart(document.getElementById(‘chart_div’));
        chart.draw(data, options);
        }

  3. HI Sir,

    I am new to Grails Framework, Examples are really helpful thank you very much

    Could you please gives us example using geolocation plugin
    Mainly if company domain object registerd with adress how to find the logitude and latitude .
    and we should get distance of KM from curent postion of employee domain to registred company.
    Please kindly help or guide me to solve this mini assignment. Thanks in advance!

  4. @Berto,

    Please try the following two commands at the command line,

    > grails clean
    > grails compile –refresh-dependencies

    If you have the MySQL driver (e.g. mysql-connector-java-5.1.21-bin.jar) in the lin folder these two commands may get rid of the error.

    Thanks.

    • What kind of compilation prmolebs did you run into before? I am currently using IDEA 8.1.3 #9886 with its JetGroovy plugin, Grails 1.1.1. I created a Grails module which depends on existing Java modules in the same project. However, when I try to run the Grails application (run-app), the depending Java modules jars are not on the classpath, thus my Java code can’t compile in groovyc steps.Do you have any ideas? Thanks

    • Not directly. iOS apps are built in Objective C, whereas Grails apps compile into Java bytecode.

  5. Thankz 4 ur great reply,I have found All over world only 234 websites has launched in Grails. where as in java many more??why,can u explain it?

    • I don’t have any visibility into sites that are implemented with Grails. Perhaps someone on the forum at grails.org has more experience in that area. There are also many experts on the forums at stackoverflow.com, and on the Grails page on Facebook.

    • Li: I am having the same prbleom. Our grails app depends on two external Java Modules as well. I have set up the grail module to depend on those two external modules, but the minute I try to build or run the app, I get a compiler error stating it cannot find the classes in those external modules.The only way I have round to get around it is to JAR those modules up and stick them in the LIB directory. Kind of a pain if you ask me.

    • You aren’t really switching. You are just adding more capabilities such as dynamic typing, closures, etc to Java’s capabilities. Groovy can utilize the majority of Java’s libraries and you can directly call Java classes and vice-versa. Grails gives you a model-view-controller framework for building enterprise-class web applications that would be much more difficult with Java alone – and with the addition of a few libraries, your application packages up into a jar file that will run on your existing Java server infrastructure.

    • Ted,I’m not sure what you mean by open your server . There is no rueqirement for projects that use cometd to be open source.Jetty never suspends a request for you. You have to decide to suspend your self. Typically I would not recommend suppending for a DAO layer as there are no async JDBC implementations that you can use to take advantage of this . Instead I would suspend on a JDBC connection pool if there were no connections available this is what the QoSFilter is for.You don’t have to use cometd to use continuations.

    • That’s hard to say for The Java Tutorial some of the parts really show their age. But if it’s not, I wonedr whether calling #setFullScreenWindow only will be enough. I mean, why all the code (in the tutorial) when all you need is a single statement?

      • hi greg,first off, thanks for the sorfwate, your time, this blog and your replies. my previous question might be a little ambiguous. since i’m using cometd, i’m trying to tie the dao layer to the ajax layer. i’ve been experimenting with the examples for 2 whole days and have a better understanding now. i read all the docs on the jetty website, but couldn’t find any examples on how to apply the QoSFilter on the ContinuationCometServlet (since i’ll be calling the dao layer from the servlet). is this the right way to do it (or is there a better way)? any suggestions on this?thanks

      • All of my code is within the Grails app mldoue, so can’t say I’ve come across that.One thing that comes to mind is whether IDEA is generating a jar file for your Java mldoue, and placing it within the grails app.. IDEA probably delegates to the grails run-app’ command, and probably requires all of the classes/jars to be available on the filesystem in the standard grails app structure.

    • hi greg, open my server was a typo. soimmetes a type faster than i think . i meant to say to open a (long-polling) connection to my server. i understand that a QoSFilter can be used on servlets, but i don’t understand how to link up a QoSFilter and the dao layer. is there an example on how to configure this? if not, could you please give me a small one?also, i’m planning on using cometd now, but i want to learn how continuations work so are there examples of using continuations in a small test/example without using cometd?thanks for the info,ted

      • I thing it’s legal to describe Groovy on Grails as Ruby on Rails for Java as it was the early idea of the dereolpevs of Grails to establish a similar framework.And yes! Groovy itself is really enjoyable and I like the idea of Grails.Greetings from Germany. Nice blog!

    • For everything that I have done, yes. Grails views use standard HTML, CSS, JavaScript, etc. You can also include Groovy Tag Libraries, which get converted to HTML before they are sent to the browser.

    • hi greg,i’m interested in using jetty’s cnutinoations, but it’s a little confusing for me because i only have a few months of ajax experience. can you clarify something for me please?i’m not using cometd as i don’t need an open to my server.here’s my scenario (without cometd):1- user sends a request2- request is suspended’3- dao layer process4- dao process completes5- resume’ and send datahow do i do this with cnutinoations? should i be using cnutinoations or does jetty take care of suspending the thread while resources are used by the dao layer, and then resume when sending data back to the requester?also, do i have to use cometd to use cnutinoations?thanks,ted

    • I ve solved the prbelom Actuallz windows installer made a dir with name grails inside my grails installation folderfor exampleC:\Grails\grailsand i had declared GRAILS_HOME =C:\Grailsnow i have changed it GRAILS_HOME=C:\Grails\grailsthen typed command like grails -vand everything worked fine

    • Dojo is a JavaScript library that lets you create rich client-side pages. Grails is a Groovy/Java -based framework, containing components for all aspects of enterprise web application development. I believe that you could integrate dojo into your Grails views for an even richer end-user experience.

  6. It would be nice if the login.gsp file didn’t show the Logout button if the user wasn’t logged in. Maybe with something like :

    • <g:if test=”${session.user}”>
      <li><g:link class=”list” action=”logout”><g:message code=”Logout” args=”[entityName]“/></g:link></li>
      </g:if>

  7. Thank you very much for this level of tutorial on Grails 2. I learned a lot. Can you post more videos on the removing the default index page from Grails framework and other stuffs like creating complex form for multiple domains. Eagerly waiting for those tuts.

  8. Hi,

    I’m trying to connect my grails app to a mysql database, but it doesn´t work. When I execute runapp command, the error message (its too long) says “Cannot create JDBC driver of class ‘com.mysql.jdbc.Driver’”

    I’ve downloaded mysql connect, and i’ve putted jar file into lib directory of my app. Could anybody helps me please?

    thnks a lot