Category Archives: Grails and Griffon

Membuat aplikasi CRUD dasar menggunakan Grails

Grails merupakan framework bentukan dari Spring yang bersifat robust dan agile. Terinspirasi oleh ruby, akhirnya framework grails memiliki kapabilitas sepertu Ruby, bahkan saya katakan lebih baik. Dalam implementasinya, setelah menginstall Grails dalam OS dan setup aplikasi, Grails dapat membuat aplikasi CRUD dengan sangat cepat karena telah memiliki standar dalam scaffolding sebuah aplikasi, yakni meliputi MVC ( model , view dan controller ). Terminologi dalam konsep MVC Grails, Model dinamakan domain. Setelah domain dibuat, developer dapat men-generate view dan controller secara otomatis menggunakan command atau terminal. Sehingga, developer hanya perlu memikirkan business process aplikasi yang akan dibangun. Dalam kesempatan kali ini, saya akan share bagaimana membuat aplikasi CRUD dengan sangat cepat menggunakan Grails. IDE yang akan saya gunakan kali ini adalah Intellij IDEA. Tapi hal ini bias di gantikan oleh Eclipse, Netbeans, STS ( Spring Tool Suite ), GGTS ( Groovy and Grails Tool Suite) So, let’s start it.
1. Buat project

2. Spesifikasikan Grails sebagai framework yang akan digunakan, dan masukkan nama project

3. Struktur project aplikasi Grails. Domain classes, merupakan directory model/ POJO. Contollers directory untuk membuat business logic aplikasi. Views, merupakan directory file gsp ( servlet dalam grails ). Configuration directory untuk setup konfigurasi program. Services directory untuk menyimpan service aplikasi. Web-app untuk menyimpan file- file tambahan untuk mempercantik web seperti image, css dan java script.

4. Jalankan aplikasi grails apakah sudah bisa berjalan dengan baik atau belum.

5. Aplikasi Grails dipastikan bisa berjalan dengan baik apabila browser dapat menampilkan gambar seperti berikut

6. Selanjutnya, kita akan membuat satu domain Bank dalam project ini, yang nantinya akan otomatis men-generate controller dan view.

7. Domain Bank diatas, mirip seperti POJO pada umumnya, hanya saja tidak ada method getter dan setter. Static mapping berfungsi untuk custom display data dalam aplikasi yaitu penambahan time stamp dan sorting berdasarkan bankcode. Static constraints berfungsi seperti constraints dalam JPA pada umumnya yaitu untuk memvalidasi inputan dari user dengan batas- batas tersebut. Setelah membuat Domain, maka Controller dan View dapat degenerate secara otomatis.

8. Tampilan Controller dan View setelah degenerate Otomatis menggunakan IDE.

9. Jalankan aplikasi Grails kembali, kemudian akan Nampak salah satu url BankController. Yang mana link tersebut akan menuju scaffolding untuk domain Bank

10. Tampilan Scaffolding domain Bank. Untuk menambah data, kita gunakan New Bank

11. Penambahan data dalam domain bank. Penyimpanan data ini hanya bersifat sementara ( dalam memory ) karena kita masih belum men-set penyimpanan kedalam disk.

12. Tampilan dalam bentuk table dari data yang telah disimpan. Kita bisa melakukan modifikasi maupun penghapusan data melalui link dari masing- masing data yang ada.

13. Apabila salah satu link di klik, maka akan mengarah ke detail data tersebut. Dan terdapat tombol untuk edit maupun delete dari data yang dipilih. Proses diatas merupakan delete data setelah view detail.

14. Proses berikut menunjukkan data sedang di-update setelah view detail

15. Hasil dari data yang telah diupdate.

Advertisements

7. Runtime (System Level Process) using groovy

System level process means create program that interact to system level to process code written in program. In UNIX, we usually do system level process through terminal meanwhile, on windows system we usually use command prompt (cmd). All the process on system level can actually be done by using program. In java we usually call it with runtime process. There are several steps to do it in java. First, we need to import java.io then, inside of try and catch block, we need to use instance of Process object to execute the command. And for the output, we can use BufferedReader as the temporary container. Here is the example :

class RuntimeProcess{
    public static void main(String [] args){
        String command = "help";
        Process p = null;
        try{
            p = Runtime.getRuntime().exec(command);
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String result = "";
            while((result = br.readLine()) != null){
                System.out.println(result);
            }
        }catch(Exception e){
            System.out.println("error "+e);
        }
        finally{
            if(p!=null){
                p.destroy();
            }
        }
    }
}


As we know that the process above there quite complicated and need a long way to code. On the other hand, groovy has GDK as the extension of JDK or it’s called Groovy JDK. We can do runtime in quite simple on line code and see the output directly there. By using [COMMAND].execute here is the code.

So, which one do you choose long and complicated or the simple and sweet one. 

6. Various of looping in Groovy

We can actually improvise our way in writing code to be more comfortable to be read, or simpler to code. By using several add from groovy we can improvise those traditional loops into modern one. We have 3 new ways to make it different from the traditional one. We can choose which one is the best for us. I think it depends on how the way we code and read it. Let’s learn it by the example

public class TraditionalLoop{
    public static void main(String[] args){
        for(int a=0 ; a<3; a++){
            System.out.println("Hello World");
        }
    }
}

Here is the result

Improvisation :
Type 1:

for ([VAR] in [STARTLOOP]..[ENDLOOP]){
     //statement
}

Type 2:

[STARTLOOP].upto([ENDLOOP]){
        //statement
}

Type 3:

[NLOOP].times{
     //statement
}

For the last one, if we want there is skip values while looping, we can use
[STARTLOOP].step( [NLOOP], [NSKIP] ) method. Here is the example :

5. Groovy Closure


Groovy closure is one of feature available on groovy. The function of this feature is like a method in java or any other programming language. We can modify variable, assign parameters or even manipulate a method. The differences between java method and groovy closure is :
1. Java method needs object initialization from the class that contain method we need. On the other hand, groovy doesn’t need that.
2. There is no visibility in groovy closure. But every single method in java must have visibility(public, private, protected).
3. There is differences in the way to write the code
Based on list above, actually we don’t have to worry about which one that we have to use in groovy, because we can use both of them whether java method or groovy closure. This is the sample code to use groovy closure.

4. XML Builder in Groovy

XML (extensible markup language) is one way/ method to dynamically move data from one program to another program. Even though XML makes programmer easy to move data, but programmatically XML is very difficult to implement using most programming language and of course it will take a lot of time for programmer to do it. Fortunately, groovy has made it easier we can create, load(read) or even modify XML document without very long and dizzy code. For example, I’d like to create XML just like previous program(Employee.java) here is the XML output :

<Employee>
	<name>Achmad Fauzi</name>
	<address>Jember</address>
	<JobDescription>Programmer</JobDescription>
</Employee>

For reference I’d like to use java code to generate that XML document. I think I takes a lot of time

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class EmployeeXML {

	public static void main(String argv[]) {

	  try {

		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

		// root elements
		Document doc = docBuilder.newDocument();
		Element rootElement = doc.createElement("Employee");
		doc.appendChild(rootElement);

		// name elements
		Element name = doc.createElement("name");
		name.appendChild(doc.createTextNode("Achmad Fauzi"));
		rootElement.appendChild(name);

		// address elements
		Element address = doc.createElement("address");
		address.appendChild(doc.createTextNode("Jember"));
		rootElement.appendChild(address);

		// jobDescription elements
		Element jobDescription = doc.createElement("JobDescription");
		jobDescription.appendChild(doc.createTextNode("Programmer"));
		rootElement.appendChild(jobDescription);

		// write the content into xml file
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(new File("D:\\employee.xml"));

		// Output to console for testing
		// StreamResult result = new StreamResult(System.out);

		transformer.transform(source, result);

		System.out.println("File saved!");

	  } catch (ParserConfigurationException pce) {
		pce.printStackTrace();
	  } catch (TransformerException tfe) {
		tfe.printStackTrace();
	  }
	}
}


And the result is

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Employee>
	<name>Achmad Fauzi</name>
	<address>Jember</address>
	<JobDescription>Programmer</JobDescription>
</Employee>

As you can see from the code above it was really – really a long code. Can you imagine if we create long, nested and complicated XML file. How to code will be like ?
Evolution has come, by using groovy we can remove those long codes to be like this


def builder = new groovy.xml.MarkupBuilder()
builder.employee{
    name "achmad fauzi"
    address "jember"
    jobDescription "programmer"
}


That’s it. We only need 6 lines to make that XML document. Absolutely it saves a lot of our time instead of using native java or another programming language.

references : http://www.mkyong.com/java/how-to-create-xml-file-in-java-dom/

3. Get Rid Of Main

Based on doctrine of JAVA, for every single program must have one class and one main method. The future of java in 21st century is groovy which is capable to make java better. One of unique thing that make groovy is a rapid programming language is non existence of main method. We don’t need to make a main method in every single groovy program, but not only that class is also unnecessary to be used in groovy program. This is the example from previous program (Employee.groovy)

public class Employee{
	String name
	String address
	String jobDescription
}
		def employees = [
			new Employee(name:"Achmad", address:"Jember", jobDescription:"Programmer"),
			new Employee(name:"Fauzi", address:"Bangkalan", jobDescription:"Artist"),
			new Employee(name:"Fauzi Achmad", address:"Jember", jobDescription:"Web Designer")
		]
		employees.each{
			println "${it.name} ${it.address} ${it.jobDescription}";
		}


From the script above, I compile and run the program using groovy console. Well, everything is more simple and easy. For most java developers don’t need to learn too much in this programming language because groovy is very familiar with java. This is another example :

2 Make it More Simple and Powerful

As dynamic programming language, groovy can be used to minimize java code into more simple and powerful code. From the previous article, I write Employee.java to be Employee.groovy that is still with the same code but different extension. But now, we will make that code to be more simple one.


public class Employee{
String name;
String address;
String jobDescription;

public static void main(String [] args){
List<Employee> employees = new ArrayList<Employee>();
employees.add(new Employee(name:"Achmad", address:"Jember", jobDescription:"Programmer"));
employees.add(new Employee(name:"Fauzi", address:"Bangkalan", jobDescription:"Artist"));
employees.add(new Employee(name:"Fauzi Achmad", address:"Jember", jobDescription:"Web Designer"));

for(Employee employee:employees){
println "${employee.name} ${employee.address} ${employee.jobDescription}";
}
}
}

From the code above, we can analyze that import, setter, getter and constructor does not need to be written again. Not only that, check out the output command : we don’t need to write System.out.println() again, but only simple “println” code which is capable to combine between variable and string in one apostrophe sign. It is so great, isn’t it ? On the other hand, we can change for command to be


public class Employee{
String name;
String address;
String jobDescription;

public static void main(String [] args){
def employees = [
new Employee(name:"Achmad", address:"Jember", jobDescription:"Programmer"),
new Employee(name:"Fauzi", address:"Bangkalan", jobDescription:"Artist"),
new Employee(name:"Fauzi Achmad", address:"Jember", jobDescription:"Web Designer")
]

employees.each{
println "${it.name} ${it.address} ${it.jobDescription}"
}
}
}

As the native List and ArrayList class groovy can convert it into their own mode by using def command. Def means anything, we can make variable or method using that command. The next explanation is keyword it. That command same as this keyword in java. So, the conclusion is, we can make java program more simple and more powerful using groovy