Understanding Grails Framework at The 1st Sight

Hi readers, it’s been a long time we haven’t met yet. I’ve been drop to the jail of daily routine that make me hard to find a time to write something here. I wrote some notes on my primary blog, and I can’t find a good idea to write something here. But it will change, I have something to share it here now..:p

I have impressed by Grails Framework, for the past 4 weeks, I’ve spent my time to go deeper to understand this framework. I don’t understand Grails Framework definition and description, but you can open their home page if you find your self in curious about it. What I want to share about Grails Framework here is, my notes when I tried to use this framework. It’s more like a steps for understanding Grails Framework manually. Okay, I’m gonna cut these craps and go straight to the point of this notes.

Okay, before the notes begin, I assumed you have installed the grails framework on your system and set the grails home installed directory to your system environment variables, here we go:

1. Create grails application.

Open the command prompt and execute below command:

E:\Data\MyProject\Grails>grails create-app grails-test
| Created Grails Application at E:\Data\MyProject\Grails\grails-test

This command will create a directory named grails-test containing the grails project skeleton

2. Create the controller

After entering the generated directory, lets create a controller called HomeController by executing this command :

    E:\Data\MyProject\Grails\grails-test>grails create-controller com.mygrails.coba.Home
    | Created file grails-app/controllers/com/mygrails/coba/HomeController.groovy
    | Created file grails-app/views/home
    | Created file test/unit/com/mygrails/coba/HomeControllerTests.groovy

Okay, I also put the prefix com.mygrails.coba before the words Home as a package of the HomeController will be placed. You can see above, when the command executed successfully, the command create a Home Controller file and stored the file at grails-app/controllers/com/mygrails/coba/ folder. by default HomeController file will contained at least with one method. This command also create a folder under the grails-app/views/ named as home too, this is the folder where we will store the viewer layer (gsp’s files) later. When we open the HomeController file, we can see the default method created like this screenshot:

package com.mygrails.coba

class HomeController {

   def index() { }

In using of Grails Framework software development. I’m a unit-test ignored person, so let’s ignore the created unit-test file..:P

4. Create the viewer layer.

And then let’s create viewer layer which is gsp file, as mentioned above, this file should be located at grails-app/views/home folder. So use your best text editor to create the index.gsp file and store it to the folder. I use notepad to create the file by executing this command:

E:\Data\MyProject\Grails\grails-test>start notepad grails-app\views\home\index.gsp

I write the content of the index.gsp file using common html tag like this:

     Welcome to Grails Framework

5. Run the application.

After the file saved let’s run the application by executing this command:

    E:\Data\MyProject\Grails\grails-test>grails run-app
    | Running Grails application
    Sep 10, 2013 10:19:00 PM org.apache.coyote.AbstractProtocol init
    INFO: Initializing ProtocolHandler ["http-bio-8080"]
    Sep 10, 2013 10:19:01 PM org.apache.catalina.core.StandardService startInternal
    INFO: Starting service Tomcat
    Sep 10, 2013 10:19:01 PM org.apache.catalina.core.StandardEngine startInternal
    INFO: Starting Servlet Engine: Apache Tomcat/7.0.39
    Sep 10, 2013 10:19:01 PM org.apache.catalina.startup.ContextConfig getDefaultWebXmlFragment
    INFO: No global web.xml found
    Sep 10, 2013 10:19:01 PM org.apache.catalina.core.ApplicationContext log
    | Server running. Browse to http://localhost:8080/grails-test

6. Open the application.

Use your favorite browser to open the application by entering this http://localhost:8080/grails-test/home/index to the address bar of the browser. You should see the result like this:

OpenApp5. Proof Grails Framework run time changed code.

Next task is modifying the content of gsp file by adding more words or html tag, remember we do this without stopping the running Grails Application. After we did the task and saved the changed gsp file, try to refresh the browser by pressing F5. When the content of opened page in the browser changed, I can consider we understood that the grails framework doesn’t need to stop and start the running application while we changed the content.

6. Passing data from controller.

Now we ready to move to the next task which is passing the data from controller layer to viewer layer in order to make us understand how these two layers can communicate each others. Open your HomeController.groovy file using your favorite text editor, and insert the code inside the index method, just like below example:

def index() {
  def name = params.name

and then edit the index.gsp file to display the data from controller just like below:

    This application powered by Grails Framework

After all the files saved, try to refresh the browser and add the url parameter to the URL address like this http://localhost:8080/grails-test/home/index?name=Stevie, we should see the content changed. And I hope we could understand that url parameter name  sent from browser, and then catch by the controller and then the controller send the parameter value to gsp file to display in the browser.

ChangedCodeThat’s it, that’s my way to understand the Grails Framework at the 1st sight. With Integrated Development Editor such as eclipse or Intellijidea, grails framework will be more easier to understand especially the code syntax.

See ya..



Component Binding On Swing Framework

Dear readers, its been a long time for me not update this blog. Please forgive me, if you find there’s no new article every time you back to this blog. Well, a short story about my activity, now I’m work at an IT Consultant company, and now we are doing a government IT project. This project is using Swing framework for it’s interface. Well, I didn’t have much understanding about swing framework, finally have to meet this framework too.
As a reminder, it will be better to share what I’ve got within my new job. one of which is Component Binding on Swing Framework. Component binding on Swing Framework is an easy way to develop a swing application using Netbeans IDE. And now for this practice, we will try to implement a component binding on Swing Framework. Ok, let’s straight to the point, create a new project using netbeans, and then create 3 package as shown as below:SwingTutorial-1.0

And then, create a class in a model package as code-snippet below:

public class Users {

    private Long id;
    private String sureName;
    private String nickName;
    private Integer age;
    private String sex;
    private String phoneNumber;
    private String address;

    //constructor below
    //getter setter below
    //toString below

And then, create a dummy data class based on Users class in a data package like below example:

 * @author Josescalia
public class UsersData {

    Users u1,u2,u3,u4;

    private void init(){
        u1 = new Users();
        u1.setId((long) 1);
        u1.setSureName("Ahmad Syarif");

        u2 = new Users();
        u2.setId((long) 2);
        u2.setSureName("Dian Sari Puspita");

        u3 = new Users();
        u3.setId((long) 3);
        u3.setSureName("Purwatika Lestari");

        u4 = new Users();
        u4.setId((long) 4);
        u4.setSureName("Dodi Sukma");

    public UsersData() {

    public List<Users> getUserList(){
        List<Users> result = new ArrayList<Users>();
        return result;

And the next step is design a form using JFrame or JPanel in a gui package just like this below picture :SwingTutorial-1.1

Give a name for each component as you like, in this tutorial I gave a tblUsers as a name for JTable component. And the type a few code like this example:

//import a few standard library, auto generate will be execute by netbeans here

public class FormExampleJTable extends javax.swing.JFrame {

    private UsersData data = new UsersData();
    private List<Users> usersList = new ArrayList<Users>();
     * Creates new form FormExampleJTable
    public FormExampleJTable() {

    private void initialize() {
        usersList = data.getUserList();

    public List<Users> getUsersList() {
        return usersList;

    public void setUsersList(List<Users> usersList) {
        this.usersList = usersList;

   //a few code will be generated by netbeans here

Notes : the code that I wrote above is only the main code, others are automatically generated by netbeans. Now let’s understand these codes before we move to the next steps.
There’s a few variable declarations, one of which is a data variable which has UsersData object data type, and the usersList variable which has an object List data type.  And then in the constructor of the class, we have a statement which call initialize method, while the initComponent method, is a method which netbeans auto generated method by default. And we can see getter and setter method for a userList variable also. In this initialize method is a core of our practice for this tutorial, please pay attention at a initialize block method, we call data.getUserList and then we patch the result to userList variable:

private void initialize() {
   usersList = data.getUserList();

By finishing this step, actually we finished the coding part, and the next steps are bind the component which in the form that we already created before. Let’s go to the main purpose this article which is Component Binding.
For the first bind we will do it in a JTable, right click the JTable component and the click properties. In the properties window, choose binding tab, and then click a small button which located horizontally to the element row, when the bind window appear, choose Binding Source to Form, and the Binding Expression to a userList variable, as shown to below picture.
If the userList variable is not show up on the list, it’s because we don’t create a getter and setter method.
After that, we can run the form and you can see the data which we created in a UsersData class contained in JTable. If we want to change the JTable looks, we can do it by right click the JTable component and choose Table Content, and then choose Column tab, at that window we can change the header, field size and other JTable settings.
Now, let’s try to bind a JTextField component, which already created on the form. The steps is exactly same with the JTable binding above, but the binding source is not Form anymore, but the JTable its self, and the Binding Expression  is selectedElement_IGNORE_ADJUSTING.[a property name of user class]. What we should noted here is property name of User class. I mean if we want to bind a JTextField to hold a sureName data from the Users class, then the binding expression must point to the selectedElement_IGNORE_ADJUSTING.sureName . As shown as below picture:

SwingTutorial-1.3Ok now, please bind all the JTextField component which exist on the Form by repeating above steps,  and then run the form. And click one of the row on a JTable, the each JTextField should contains the each data according to the row we have clicked on JTable.
That’s all for the practice now, this link is a project source code of our practice that you are free to use, develop and try by your self.
Have good day, and I hope it useful.



Using TestNG on Spring Framework and Hibernate Test Case

Dear readers, at the time I wrote this article, I just have 2 months of being an employee at the IT Consultant Company in Jakarta, Indonesia. But that’s not what I want to share in this article. In this company, I was expected to follow the java development stack which is applied in this company. The Spring Framework and Hibernate are include.

I’ve been 6 years in Java programming language, but I admit, I never involve Hibernate framework as an ORM(Object Relational Mapping) method on my projects development stack. While Spring Framework, I’ve been using it since 2 years ago. This condition force me to do a little adaptation of this Hibernate Framework.

I often met some difficulties which is stress me so much, when the codes of the dao layer using a hibernate criteria. For a few developers who always using hibernate framework, it should be easier to use hibernate criteria, but for me, it really stress me so much.

To find a method on a dao layer work or not, sometimes it wouldn’t so effective to test it by deploying whole application just only to test one method. And I decide to use unit-test when testing dao layer methods, so I don’t need to deploy whole application.

Okay, below is the step to create a unit-test in order to test the methods on dao layer which created using Spring Framework and hibernate:

  1. Create a hibernate configuration file, Spring Context file, and all those supported files, and put them onto test/resources folder just like the picture below:
  2. Create a file called TestDao, and put it onto test/java folder. The codes of the files is below:
package com.mojo.maven.test;

import com.mojo.maven.dao.NewsCategoryDao;
import com.mojo.maven.dao.NewsDao;
import com.mojo.maven.model.News;
import com.mojo.maven.model.NewsCategory;
import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.hibernate.context.ManagedSessionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class TestDao extends AbstractTestNGSpringContextTests{
    private Logger logger = Logger.getLogger(TestDao.class);

    public SessionFactory sessionFactory;
    private Session session;

    private NewsDao newsDao;

    private NewsCategoryDao newsCategoryDao;

     * Inisialisasi hibernate context sebelum test
    void init() {
        logger.debug("init session factory");
        session = sessionFactory.openSession();

     * cleanup hibernate context setelah test
    void destroy() {
        logger.debug("destroy session factory");

    public void testGetNews(){
        News news = newsDao.getById(1);
        logger.info("News ID : " + news.getId());
        logger.info("News Title : " + news.getNewsTitle());
        logger.info("News URL : " + news.getNewsUrl());
        logger.info("News Category : " + news.getNewsCategory().getCategoryName());
        logger.info("News Category Description : " + news.getNewsCategory().getCategoryDescription());

What we have to pay attention on the class are, the class have an annotation @ContextConfiguration and extends AbstractTestNGSpringContextTests class which is provide as a base class to use it as a test class for TestNG Framework. Also on the annotation @ContextConfiguration  defined the location of the Spring Context, so the compiler can find a Spring Context file when the execution is triggered.

The next thing which have to note are 2 methods which is defined on the class, those are void init() method and void destroy() method. void init() method, given an annotation @BeforeMethod which have a function as an hibernate context initializations before all other the test method executed. While void destroy() method given an annotation @AfterMethod which have a function to close a hibernate session after all test method executed.

Well, that’s all that I can share for this time. If you feel the codes need more improvement, so go head, to make it perfect.

I’ll hope it usefull.