Category Archives: Groovy

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. 

Advertisements

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

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.