Monthly Archives: August 2013

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.

Advertisements

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

1 Getting Started With Groovy

Image taken from : groovy.codehaus.org

Groovy is an extension programming language from java(dynamic programming). It is about how do you write code more simple and more powerful without need to decrease the capability of java it self. For java programmers, I think to move into groovy will not be too hard because what did you do in java, you can do it in groovy without need to change anything. Moreover, we can make java code to be more simple. And still there are more capability that groovy can do besides those all. I’d like write them one by one through this blog.

But first let’s install groovy into our computer. To make it easy here I use windows operating system.

  1. Download the most recent stable groovy binary release from
  2. Extract groovy-binary x.x.x.zip to your hard drive location
  3. Set a GROOVY_HOME environment variable
  4. Add the %GROOVY_HOME%\bin to your system path

Usually all of process above can be processed automatically if you download groovy for windows installer. I think it will be easier without more effort.

Well let’s continue to next part. As I explain before, what you can do in java, you will be able to do it in groovy. Here is an example java code using POJO(Plain Old Java Object)/ java bean:

import java.util.List;

import java.util.ArrayList;

public class Employee{

String name;

String address;

String jobDescription;

public Employee(){}

public Employee(String name, String address, String jobDescription){

this.name = name;

this.address = address;

this.jobDescription = jobDescription;

}

public String getName(){

return name;

}

public void setName(String name){

this.name = name;

}

public String getAddress(){

return address;

}

public void setAddress(String address){

this.address = address;

}

public String getJobDescription(){

return jobDescription;

}

public void setJobDescription(String jobDescription){

this.jobDescription = jobDescription;

}

public static void main(String [] args){

List<Employee> employees = new ArrayList<>();

employees.add(new Employee("Achmad", "Jember", "Programmer"));

employees.add(new Employee("Fauzi", "Bangkalan", "Artist"));

employees.add(new Employee("Fauzi Achmad", "Jember", "Web Designer"));

for(Employee employee:employees){

System.out.println(employee.getName()+" "+employee.getAddress()+" "+employee.getJobDescription());

}

}

}

From source code above, we can convert it easily by changing the extension of Employee.java become Employee.groovy. to run it, we don’t have to complete then run, because groovy has done it once. This is the example.

August 9th 2013

It’s been long time I didn’t publish anything into this blog. There are several circumstances that I’ve to finish to accomplish my problems ahead. But, by this publish forward I’d like to share with all people around the world through this internet facility about something I’ve learned from the pass. I do believe that there are a lot of wisdom from every single human’s experience that we should take and learn to face and be better in the future.

I know and realize that I am an ambitious man. Last semester in my study I actually don’t have any class. I only need to focus into my final assignment(thesis) as requirement for a bachelor in computer science major. Day by day I do it well, I think that I will graduate faster than my classmate. But, in the middle of the process, one of my project’s client ask me to customize their program and they want me to be someone who can lead them to collect data for program. I know that life is choice, we have to map between risk and priority. If I help my client à I won’t finish my thesis, on the other hand if I keep on my thesis à my client will be disappointed of me and I won’t get easy money. Finally, I pick up the first option. I was wondering that I can finish the project and also my final assignment in an action.

Day by day I work for both of them, project and thesis. But, in the final there must be one of them left and one of them passed. And the left one is my thesis. I can’t finish it cause I don’t have enough time to accomplish. One again, life is a choice, we must consider priority and risk to do the best for our own life.

Because in the last semester I planned to make a book for grails, and it didn’t come true, So that, I’d like to finish it through this blog. Started from groovy and then grails after that I’ll continue to griffon. I hope all of them can be done fluently until my writing goes to be a real book and published.