Programing Assignment 1 – Building Your First Grails Apps

The purpose of this assignment is to introduce you to Grails and includes:

  • Grails Frame work including Domain, Controller and Views
  • GGTS integrated development environment
  • Database and dbconsole

You are to complete this programming assignment individually. In this assignment you will build a simple web app for a book store’s administrative backend, meaning administrators will be able to add books and authors to the book store’s database.

Step 1: Watch Introduction to Grails videos Grails Example

Point your web browser to

http://www.grailsexample.net/introduction-to-grails/

This is the first video of a series of 15 tutorials. You are to watch all the videos. This will take about 90 minutes. The video are well produced and give a good introduction to the basics of grails. You can get to the following video tutorials by clicking on the “Next” arrow just below the page’s navbar and on the right side.

The first tutorial explains the Grails frame work. The following videos explain the installation process for different operating system. You only need to watch the installation video for the operating system of your home machine, but do NOT install Grails and GGTS as you watch the video instead follow my instructions in step 2 of this assignment. It is much simpler.

Video 8 through 12 show how to build the basic stack for a web app, model (domain class), controller and views. Video 13 goes into more detail about the model and the power of Grails GORM. Video 14 and 15 explains dynamic and static scaffolding. You will want to use static scaffolding to complete this assignment.

If you need more resources consult the Grails User Documentation

http://grails.org/doc/latest/

In particular, you will want to study chapter 7 about GORM to learn more about how to make and use Grails models

http://grails.org/doc/latest/guide/GORM.html

For more details about Grails views and controllers, you will want to study chapter 8 about the web layer

http://grails.org/doc/latest/guide/theWebLayer.html

Also on the right hand side of all the documentation web pages is the Quick Reference, but you need to have a wide browser window to view the links in the quick reference.

The documentation is a good reference but is very technical, so you will probably find it hard to understand when you first begin programming. There are good books that give easy explanation of grails.

https://grails.org/Books

Step 2: Install an IDE and Grails on your home machine

There are two options for an IDE, JetBrian’s IntlelliJ or Spring’s GGTS. They both are good. IntelliJ is perhaps better because it has more code completion, but the installation is more complex. Installing IntelliJ requires registering a student account with JetBrians and downloading Grails separately. While for GGTS, there is no registration and only single download is necessary.

Below is detail instruction for both IntelliJ and GGTS, first IntelliJ and second GGTS

Step 2a: Install IntelliJ IDE and Grails on your home machine and get it running.

The instructions are specific to a Windows machine. If you are using Mac or Linux it might differ some.

1. Register a student account with JetBrians.

You will need the ultimate version of IntelliJ for Grails develop, which does cost approximately $200 unless you register as a student. The registration allows you to use IntelliJ for a year.

Register at

https://www.jetbrains.com/estore/students/

using your MTU email. You should quickly get an email from JetBrians Sales with subject line “JetBrians Student License Confirmation.” In the email, there should be a link to “Activate Educational License.” Follow the link and the instructions. You should use your email address for your username and you can create your own password. Record the password, you will need it later to finish the installation of IntelliJ.

2. Download and Unzip Grails.

You can get the latest version of Grails at

https://grails.org/download

Click on the green button titled “Download Grails X.X.X” and an zip file should download. Unpack the zip file into any directory. I make a c:/grails/ director and unzip into that directory.

2. Download and Install IntelliJ.

Go to:

https://www.jetbrains.com/idea/download/

The correct operating system tab should be open, but check. Then click on the blue “Download Ultimate” button. You do NOT want the community version. It does not have support for Grails.

After clicking the download button, a exe installation file should download. When it is finished downloading, run it as an administrator. You can accept all the defaults. It will but the IntelliJ executable and other necessary files in

C:\Program Files (x86)\JetBrains\IntelliJ IDEA 14.0.1\

3. Create your Projects directory before you start IntelliJ.

IntelliJ’s default projects space or workspace is in c:\Users\Username\Projects\ folder.I rather have several workspaces for the different projects. For example, for this course you may want a workspace for the programming assignment and another for the project.

4. Start IntelliJ.

IntelliJ introductory screen does not request a workspace or a project space to open. Instead you specify the project space location when you create a new project.

Step 3a: Make the Grails project using IntelliJ.

1. Use the wizard to make the Grails project.

From IntelliJ menu select File and then New Project. A wizard modal window should appear. In the left panel select Grails and then in the right panel click on “Web Application.” At the top is are dropdown menu for selecting the Project SDK and the Grails Library. Make sure they are filed in. If this is the Grails project you are making then you will need to specify the Grails library. Click the “Create…” button to navigate and specify the directory that you unzipped Grails.

After completing the first screen, click the “Next” button. In this screen you name the project and specify the project location.  You can use any project name, but to be consistent with the code examples in this programming assignment and the next assignments, you want to name the project “cs4760progassign.” For the Project location you’ll want to enter the path of the project space you made earlier. Now click “Finish.”

A potential problem: On machine a modal window will appear saying that “Windows Firewall has blocked some features…” Click “allow access” to finish creating the project.

A modal will ask with “Run ‘create-app'” or “Run ‘create-plugin'” or “Cancel.” Click the “Run ‘create-app'” button and the basic web application files will be created in your project.

2. Test that the project build.

Select your project in Project Explorer.Then right click -> Run as -> Grails Command (run-app). Or you can tap the run icon in the menu bar and select run-app. Grails and Java compile the app. When the compile is complete you should see in the console the message “Browse to http://localhost:8080/…”. Click on the link and the GGTS browser will load and show the basic index page with access to controllers.

2. Test that the project build.

From the IntelliJ menu select Run and then “Run ‘cs4760progassign’.” The console window should appear at the bottom IntelliJ frame, and you should see the progress of the progress of the compilation. When it is done a URL link should appear, “http://localhost:8080/cs4760progassign.” Click on it and your default web browser should open to the web app start page.

3. Skip to Step 4.

The above should have gotten you acquainted with IntelliJ interface. It very similar Eclipse and GGTS. Note that the rest of instructions a written assuming that you are using GGTS.   There is one difference with IntelliJ interface. Access to the different views is at the bottom of the frame. Also at lower left corner is icon that you can toggle views. Hovering the icon will show a list of other views you can access.

Step 2b: Install GGTS IDE and Grails on your home machine and get it running.

The instructions are specific to a Windows machine. If you are using Mac or Linux it might differ some.

1. Download the latest version of GGTS to your home machine into any directory

http://spring.io/tools/ggts

You will see the link on the right hand side of the page just under the Groovy and Grails emblem. The download is a zip file and takes a few minutes to download. Move the zip file to any directory (I put mine at the root of the C drive in a directory called grails). Unzip the file. (I recommend using 7-Zip for unzipping. It is faster than the Windows compress utility and can handle longer path names.) You can explore the directory structure. At the top most level it i

  • gtts-bundle
    • ggts-3.6.1-RELEASE
      • Several sub directories
      • Several files
      • GGTS.exe <- This is the executable that starts GGTS.
    • grails-2.43 <- This is Grails, the web framework.
    • legal
    • pivtal-tc-server-developer-3.0.0.RELEASE

You probably want to make a short cut on your desktop to GGTS.exe, so that you do not have to navigate using file explorer every time you want to start grails.

2. Create your workspace directory before you start GGTS.

GGTS default workspace is in your documents folder.I rather have several workspaces for the different projects. For example, for this course you may want a workspace for the programming assignment and another for the project.

3. Start GGTS.

On the introductory screen, browse to your workspace directory and hit OK. In a few minutes GGTS should load and appear. It should look familiar. GGTS is built on Eclipse. In the center is normally the editing window, but the first time starting GGTS the dashboard appears in the editing window. You do not need the dashboard so you can x-out to remove it.

Congratulations GGTS and Grails are on your home machine.

Step 3b: Make the Grails project using GGTS.

1. Use the wizard to make the Grails project.

In the left pane is the Project Explorer. Right click in the Project Explorer and select new -> project -> Grails -> Grails Project, then tap Next to start the “Create a new Grails Project” wizard. Type the project name. You may call it “cs4760progassign”. Defaults of the rest of the fields should be OK.

A Potential Problem:

Check which version of Grails the workspace is using by clicking “Configure Grails Installation” link. Note that all projects in the same workspace must use the same version of Grails. Click finish. You may have to refresh dependences. Right click your project then select “Grails Tools” -> “Refresh Dependences.”

Another Problem:

If you get an error dialogue saying “Grails requires a JDK.” The project will not build. You should already have a JDK on your machine. Check your system variable JAVA_HOME path. Check that the path is correct. If it is, go to GGTS and click Window -> Preferences -> Java -> Installed JRE and then click “Add”. In the next window, you want “Standard VM” selected and then click “Next.” In the next window, browse to your latest jdk directory and select. When you return to the “Installed JREs” window make sure that the JDK is checked. Then hit “OK”. The project should build now. For reference, see

http://stackoverflow.com/questions/14663528/groovy-and-grails-jdk-issue

Third Problem:

Comment out (delete) the grails.project.fork map. In the Project Explorer expand “conf” to view the configuration files. Double click BuildConfig.groovy. In BuildConfig.groovy file, comment out the lines from just above “grails.project.fork = [” to just below the terminating square bracket, “]”.

The fork does not work well and you do not need it. With the fork in place you’ll not be able to terminate your running app by using the red square icon in the toolbar.

2. Test that the project build.

Select your project in Project Explorer.Then right click -> Run as -> Grails Command (run-app). Or you can tap the run icon in the menu bar and select run-app. Grails and Java compile the app. When the compile is complete you should see in the console the message “Browse to http://localhost:8080/…”. Click on the link and the GGTS browser will load and show the basic index page with access to controllers.

Step 4: Make Domain Classes.

You will implement a simple database scheme. You need to table in the database, an Author table and a Book table:

Database Scheme:

Author:

  • String Name
  • has many books (list of entries in the Book table)

Book:

  • String Title
  • belongs to author (entry in the Author table)

Read the chapter about GROM in the Grails documentation to learn how to specify the Domain classes, Author and Book. Specifically, you’ll want to read carefully the section about GROM association:

http://grails.org/doc/latest/guide/GORM.html#gormAssociation

You should see that the Author class references the Book class and the Book class references the Author class. This is cyclic references and can confuse the auto compiler in the IDE, if you just write the code for the classes sequentially. If you type up the Author class before there is a Book class then your code will have an error at the line referencing the Book class. Instead of writing the classes sequentially I suggest first making both empty Author and Book domain classes by right clicking on the project, select new -> Domain Class. Fill in the name of the domain class: Author or Book, and finally “Finish.” After creating both the Author and Book domain classes, you can type the references to other class without error.

After creating the domain classes, you will want to test the compile again. If you do that you might see in the console the following error:

…
 |Running Grails application
 Error |
 2014-10-06 15:17:42,652 [localhost-startStop-1] ERROR hbm2ddl.SchemaExport - HHH000389: Unsuccessful: alter table book drop constraint FK_ad77oefv8m27ohs42aiyagj2s if exists
 Error |
 2014-10-06 15:17:42,652 [localhost-startStop-1] ERROR hbm2ddl.SchemaExport - Table "BOOK" not found; SQL statement:
 alter table book drop constraint FK_ad77oefv8m27ohs42aiyagj2s if exists [42102-176]
 |Server running. Browse to http://localhost:8080/cs4760progassign

The error is not really, rather a bug in Grails. You can point the browser to the URL and the standard start page will show. You can also inspect the database (see below) and the Author and Book tables have been created. Nevertheless, the error is annoying and confusing. To fix the bug see:

http://stackoverflow.com/questions/23858953/grails-2-4-and-hibernate4-errors-with-run-app

The basic procedure is to create the java class:

package cs4760progassign;

import org.hibernate.dialect.H2Dialect;

public class ImprovedH2Dialect extends H2Dialect {

    @Override
    public String getDropSequenceString(String sequenceName) {
        // Adding the "if exists" clause to avoid warnings
        return "drop sequence if exists " + sequenceName;
    }

    @Override
    public boolean dropConstraints() {
        // We don't need to drop constraints before dropping tables, that just
        // leads to error messages about missing tables when we don't have a
        // schema in the database
        return false;
     }
}

Right click the project and select new -> Class and then enter the name of the class, ImprovedH2Dialect. This will put the Java class file in the “src/Java” folder in your project. Copy and paste the above code into the class file.

You will also have to add a line to the DataSource.groovy configuration file. Add the line:

dataSource.dialect = cs4760progassign.ImprovedH2Dialect

Now you run the app and will not see the error message in the console.

Step 5: Inspect the database.

Point your browser to

http://localhost:8080/cs4760progassign/dbconsole

This will bring up the database login. Note that in the login screen the JDBC URL should match what is specified in the DataSource.groovy configuration file. So if you running in a “development” environment the JDBC URL should be

jdbc:h2:mem:devDb;MVCC=TRUE

The user name should be “sa” and password should be blank. Click “Connect” button and data browser will appear. You should see the Author and Book tables listed on the left panel. Expanding them you’ll see the fields for each table. Clicking the Author table will enter the SQL command:

SELECT * FROM AUTHOR

You can click the “Run” button to execute the command. Do so you’ll see that the table is empty because you have not add entries to the table.

Step 6: Add entries to the Tables.

You can use the Bootstrap.groovy configuration to add entries to the table during. Open the Bootstrap.groovy file and add the following code to the init closure.

import cs4760progassign.Author
import cs4760progassign.Book

class BootStrap {

    def init = { servletContext ->
        new Author(name:"Stephen King")
             .addToBooks(new Book(title:"The Stand", publishYear:1978))
             .addToBooks(new Book(title:"The Shining", publishYear:1977))
             .save()

        new Author(name:"Mark Twain")
            .addToBooks(new Book(title:"Tom Sawyer", publishYear:1876))
            .addToBooks(new Book(title:"Huckelberry Finn", publishYear:1884))
            .save()

    }
    def destroy = {
    }
}

Now stop the app and run it again. Point the browser to the dbconsole and inspect the tables you should see the entries in both the Author and Book tables.

Step 7: Generate the Controller and Views

Grails will generate the basic controller and all the views for the domain classes. To make the controller for Author domain class, right click the project and select “Grails Tools” –> “Open Grails Command Prompt” and type

generate-all cs4760progassign.Author

Make sure the correct project specified.

This will make several files for you:

  • controller/AuthorController.groovy
  • views/author/_form.gsp
  • views/author/create.gsp
  • views/author/edit.gsp
  • views/author/edit.gsp
  • views/author/index.gsp
  • views/author/show.gsp
  • test/unit/AuthorController.groovy

You should inspect these files and learn from them.

Generate all the Book controller and views. Inspect these files.

Step 8: Use the Web App

You can run the web app. Stop and start the app again. Starting index page should show the Author and Book controllers.

If you make a change to the Domain class you’ll have to generate all the controllers and views again. The generate-all command will ask you to replace the files. You may need to delete all the generated files before you can make them again.

Use the app to create a new author and add a book to the author. View the Author and Book list to see that it is in database. Also go to dbconsole to inspect the tables directly.

Delete the author “Stephen King” and then view the book list. The books “The Stand” and “The Shining” should be gone from the list. This is because of the static property “belognsTo” in the Book domain class.

Step 9: Change Cross Reference Listings

Using the web app, you should have noticed that when you show an author the books that are listed are referenced by the table (cs4760progassign.Book) and the id. Also showing book list shows the authors by the table and the id. This is not an error but it might not be what you want. You probably expect that the book reference ought to be the book title and the author reference should be the author’s name. We can change the behavior by adding a toString method to the domain model.

In the Author domain class, add the lines below:

String toString(){
 "${name}"
}

In the Book domain class, add the lines

String toString(){
 "${title}"
}

You’ll need to stop and run the web app again for the changes to the domain to take place. Now ty the web app, you notice that Author is referenced by name and Book by the title. The code in the toString method tells the view how to render the view. The dollar sign, $, are grails tag that alert the view that within the curly bracket is groovy code, in this case a parameter of the method.

In generally, you should be careful making these changes. The problem with our change is that the name of the author may not be unique, meaning two authors may have the same name. So, this will cause ambiguity when associating a book with an author. In the next assignment you’ll see that my general strategy is to use the generated views only for the administrated backend of the website and that we’ll make public views by hand coding. The admin should understand the references to book and author are table and id, and consequently the admin would not be confused.

Step 10: Make the Screen Shot and Email Me

After creating a new author, adding a book and deleting the author “Stephen King”, make a screen shoot of the book list. The URL is

http://localhost:8080/cs4760progassign/book/index

Email me the screen shot. The subject of the email should be

“2014 cs4760 Programming Assignment 1 Proof”

Congratulations, you have completed your first programming assignment and made your first web app.