Groovy – Dates & Times

Groovy – Dates & Times ”; Previous Next The class Date represents a specific instant in time, with millisecond precision. The Date class has two constructors as shown below. Date() Syntax public Date() Parameters − None. Return Value Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond. Example Following is an example of the usage of this method − Live Demo class Example { static void main(String[] args) { Date date = new Date(); // display time and date using toString() System.out.println(date.toString()); } } When we run the above program, we will get the following result. The following output will give you the current date and time − Thu Dec 10 21:31:15 GST 2015 Date (long millisec) Syntax public Date(long millisec) Parameters Millisec – The number of millisecconds to specify since the standard base time. Return Value − Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as “the epoch”, namely January 1, 1970, 00:00:00 GMT. Example Following is an example of the usage of this method − Live Demo class Example { static void main(String[] args) { Date date = new Date(100); // display time and date using toString() System.out.println(date.toString()); } } When we run the above program, we will get the following result − Thu Jan 01 04:00:00 GST 1970 Following are the given methods of the Date class. In all methods of class Date that accept or return year, month, date, hours, minutes, and seconds values, the following representations are used − A year y is represented by the integer y – 1900. A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December. A date (day of month) is represented by an integer from 1 to 31 in the usual manner. An hour is represented by an integer from 0 to 23. Thus, the hour from midnight to 1 a.m. is hour 0, and the hour from noon to 1 p.m. is hour 12. A minute is represented by an integer from 0 to 59 in the usual manner. A second is represented by an integer from 0 to 61. Sr.No. Methods & Description 1 after() Tests if this date is after the specified date. 2 equals() Compares two dates for equality. The result is true if and only if the argument is not null and is a Date object that represents the same point in time, to the millisecond, as this object. 3 compareTo() Compares two Dates for ordering. 4 toString() Converts this Date object to a String 5 before() Tests if this date is before the specified date. 6 getTime() Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object. 7 setTime() Sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT. Print Page Previous Next Advertisements ”;

Groovy – Meta Object Programming

Groovy – Meta Object Programming ”; Previous Next Meta object programming or MOP can be used to invoke methods dynamically and also create classes and methods on the fly. So what does this mean? Let’s consider a class called Student, which is kind of an empty class with no member variables or methods. Suppose if you had to invoke the following statements on this class. Def myStudent = new Student() myStudent.Name = ”Joe”; myStudent.Display() Now in meta object programming, even though the class does not have the member variable Name or the method Display(), the above code will still work. How can this work? Well, for this to work out, one has to implement the GroovyInterceptable interface to hook into the execution process of Groovy. Following are the methods available for this interface. Public interface GroovyInterceptable { Public object invokeMethod(String methodName, Object args) Public object getproperty(String propertyName) Public object setProperty(String propertyName, Object newValue) Public MetaClass getMetaClass() Public void setMetaClass(MetaClass metaClass) } So in the above interface description, suppose if you had to implement the invokeMethod(), it would be called for every method which either exists or does not exist. Missing Properties So let’s look an example of how we can implement Meta Object Programming for missing Properties. The following keys things should be noted about the following code. The class Student has no member variable called Name or ID defined. The class Student implements the GroovyInterceptable interface. There is a parameter called dynamicProps which will be used to hold the value of the member variables which are created on the fly. The methods getproperty and setproperty have been implemented to get and set the values of the property’s of the class at runtime. Live Demo class Example { static void main(String[] args) { Student mst = new Student(); mst.Name = “Joe”; mst.ID = 1; println(mst.Name); println(mst.ID); } } class Student implements GroovyInterceptable { protected dynamicProps=[:] void setProperty(String pName,val) { dynamicProps[pName] = val } def getProperty(String pName) { dynamicProps[pName] } } The output of the following code would be − Joe 1 Missing methods So let’s look an example of how we can implement Meta Object Programming for missing Properties. The following keys things should be noted about the following code − The class Student now implememts the invokeMethod method which gets called irrespective of whether the method exists or not. Live Demo class Example { static void main(String[] args) { Student mst = new Student(); mst.Name = “Joe”; mst.ID = 1; println(mst.Name); println(mst.ID); mst.AddMarks(); } } class Student implements GroovyInterceptable { protected dynamicProps = [:] void setProperty(String pName, val) { dynamicProps[pName] = val } def getProperty(String pName) { dynamicProps[pName] } def invokeMethod(String name, Object args) { return “called invokeMethod $name $args” } } The output of the following codewould be shown below. Note that there is no error of missing Method Exception even though the method Display does not exist. Joe 1 Metaclass This functionality is related to the MetaClass implementation. In the default implementation you can access fields without invoking their getters and setters. The following example shows how by using the metaClass function we are able to change the value of the private variables in the class. Live Demo class Example { static void main(String[] args) { Student mst = new Student(); println mst.getName() mst.metaClass.setAttribute(mst, ”name”, ”Mark”) println mst.getName() } } class Student { private String name = “Joe”; public String getName() { return this.name; } } The output of the following code would be − Joe Mark Method Missing Groovy supports the concept of methodMissing. This method differs from invokeMethod in that it is only invoked in case of a failed method dispatch, when no method can be found for the given name and/or the given arguments. The following example shows how the methodMissing can be used. Live Demo class Example { static void main(String[] args) { Student mst = new Student(); mst.Name = “Joe”; mst.ID = 1; println(mst.Name); println(mst.ID); mst.AddMarks(); } } class Student implements GroovyInterceptable { protected dynamicProps = [:] void setProperty(String pName, val) { dynamicProps[pName] = val } def getProperty(String pName) { dynamicProps[pName] } def methodMissing(String name, def args) { println “Missing method” } } The output of the following code would be − Joe 1 Missing method Print Page Previous Next Advertisements ”;

Groovy – Closures

Groovy – Closures ”; Previous Next A closure is a short anonymous block of code. It just normally spans a few lines of code. A method can even take the block of code as a parameter. They are anonymous in nature. Following is an example of a simple closure and what it looks like. Live Demo class Example { static void main(String[] args) { def clos = {println “Hello World”}; clos.call(); } } In the above example, the code line – {println “Hello World”} is known as a closure. The code block referenced by this identifier can be executed with the call statement. When we run the above program, we will get the following result − Hello World Formal parameters in closures Closures can also contain formal parameters to make them more useful just like methods in Groovy. Live Demo class Example { static void main(String[] args) { def clos = {param->println “Hello ${param}”}; clos.call(“World”); } } In the above code example, notice the use of the ${param } which causes the closure to take a parameter. When calling the closure via the clos.call statement we now have the option to pass a parameter to the closure. When we run the above program, we will get the following result − Hello World The next illustration repeats the previous example and produces the same result, but shows that an implicit single parameter referred to as it can be used. Here ‘it’ is a keyword in Groovy. class Example { static void main(String[] args) { def clos = {println “Hello ${it}”}; clos.call(“World”); } } When we run the above program, we will get the following result − Hello World Closures and Variables More formally, closures can refer to variables at the time the closure is defined. Following is an example of how this can be achieved. Live Demo class Example { static void main(String[] args) { def str1 = “Hello”; def clos = {param -> println “${str1} ${param}”} clos.call(“World”); // We are now changing the value of the String str1 which is referenced in the closure str1 = “Welcome”; clos.call(“World”); } } In the above example, in addition to passing a parameter to the closure, we are also defining a variable called str1. The closure also takes on the variable along with the parameter. When we run the above program, we will get the following result − Hello World Welcome World Using Closures in Methods Closures can also be used as parameters to methods. In Groovy, a lot of the inbuilt methods for data types such as Lists and collections have closures as a parameter type. The following example shows how a closure can be sent to a method as a parameter. Live Demo class Example { def static Display(clo) { // This time the $param parameter gets replaced by the string “Inner” clo.call(“Inner”); } static void main(String[] args) { def str1 = “Hello”; def clos = { param -> println “${str1} ${param}” } clos.call(“World”); // We are now changing the value of the String str1 which is referenced in the closure str1 = “Welcome”; clos.call(“World”); // Passing our closure to a method Example.Display(clos); } } In the above example, We are defining a static method called Display which takes a closure as an argument. We are then defining a closure in our main method and passing it to our Display method as a parameter. When we run the above program, we will get the following result − Hello World Welcome World Welcome Inner Closures in Collections and String Several List, Map, and String methods accept a closure as an argument. Let’s look at example of how closures can be used in these data types. Using Closures with Lists The following example shows how closures can be used with Lists. In the following example we are first defining a simple list of values. The list collection type then defines a function called .each. This function takes on a closure as a parameter and applies the closure to each element of the list. Live Demo class Example { static void main(String[] args) { def lst = [11, 12, 13, 14]; lst.each {println it} } } When we run the above program, we will get the following result − 11 12 13 14 Using Closures with Maps The following example shows how closures can be used with Maps. In the following example we are first defining a simple Map of key value items. The map collection type then defines a function called .each. This function takes on a closure as a parameter and applies the closure to each key-value pair of the map. Live Demo class Example { static void main(String[] args) { def mp = [“TopicName” : “Maps”, “TopicDescription” : “Methods in Maps”] mp.each {println it} mp.each {println “${it.key} maps to: ${it.value}”} } } When we run the above program, we will get the following result − TopicName = Maps TopicDescription = Methods in Maps TopicName maps to: Maps TopicDescription maps to: Methods in Maps Often, we may wish to iterate across the members of a collection and apply some logic only when the element meets some criterion. This is readily handled with a conditional statement in the closure. Live Demo class Example { static void main(String[] args) { def lst = [1,2,3,4]; lst.each {println it} println(“The list will only display those numbers which are divisible by 2”) lst.each{num -> if(num % 2 == 0) println num} } } The above example shows the conditional if(num % 2 == 0) expression being used in the closure which is used to check if each item in the list is divisible by 2. When we run the above program, we will get the following result − 1 2 3 4 The list will only display those numbers which are divisible by 2. 2 4 Methods used with Closures The closures themselves provide some methods. Sr.No. Methods & Description 1 find() The find method finds the first value in a collection that

Groovy – Generics

Groovy – Generics ”; Previous Next Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs. The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types. Generic for Collections The collections classes such as the List class can be generalized so that only collections of that type are accepted in the application. An example of the generalized ArrayList is shown below. What the following statement does is that it only accepts list items which are of the type string − List<String> list = new ArrayList<String>(); In the following code example, we are doing the following − Creating a Generalized ArrayList collection which will hold only Strings. Add 3 strings to the list. For each item in the list, printing the value of the strings. Live Demo class Example { static void main(String[] args) { // Creating a generic List collection List<String> list = new ArrayList<String>(); list.add(“First String”); list.add(“Second String”); list.add(“Third String”); for(String str : list) { println(str); } } } The output of the above program would be − First String Second String Third String Generalized Classes The entire class can also be generalized. This makes the class more flexible in accepting any types and working accordingly with those types. Let’s look at an example of how we can accomplish this. In the following program, we are carrying out the following steps − We are creating a class called ListType. Note the <T> keywords placed in front of the class definition. This tells the compiler that this class can accept any type. So when we declare an object of this class, we can specify a type during the the declaration and that type would be replaced in the placeholder <T> The generic class has simple getter and setter methods to work with the member variable defined in the class. In the main program, notice that we are able to declare objects of the ListType class, but of different types. The first one is of the type Integer and the second one is of the type String. Live Demo class Example { static void main(String[] args) { // Creating a generic List collection ListType<String> lststr = new ListType<>(); lststr.set(“First String”); println(lststr.get()); ListType<Integer> lstint = new ListType<>(); lstint.set(1); println(lstint.get()); } } public class ListType<T> { private T localt; public T get() { return this.localt; } public void set(T plocal) { this.localt = plocal; } } The output of the above program would be − First String 1 Print Page Previous Next Advertisements ”;

Groovy – Useful Resources

Groovy – Useful Resources ”; Previous Next The following resources contain additional information on Groovy. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Groovy Fundamentals Course For Testers Most Popular 53 Lectures 8 hours Krishna Sakinala More Detail Practical Guide to Jenkins 42 Lectures 2 hours Chaitanya Allidona More Detail Groovy Programming Fundamentals for Java Developers 49 Lectures 2.5 hours Packt Publishing More Detail Complete JanusGraph Course For Beginners 21 Lectures 2 hours Sanil Bagzai More Detail Print Page Previous Next Advertisements ”;

Groovy – Template Engines

Groovy – Template Engines ”; Previous Next Groovy’s template engine operates like a mail merge (the automatic addition of names and addresses from a database to letters and envelopes in order to facilitate sending mail, especially advertising, to many addresses) but it is much more general. Simple Templating in Strings If you take the simple example below, we are first defining a name variable to hold the string “Groovy”. In the println statement, we are using $ symbol to define a parameter or template where a value can be inserted. def name = “Groovy” println “This Tutorial is about ${name}” If the above code is executed in groovy, the following output will be shown. The output clearly shows that the $name was replaced by the value which was assigned by the def statement. Simple Template Engine Following is an example of the SimpleTemplateEngine that allows you to use JSP-like scriptlets and EL expressions in your template in order to generate parametrized text. The templating engine allows you to bind a list of parameters and their values so that they can be replaced in the string which has the defined placeholders. def text =”This Tutorial focuses on $TutorialName. In this tutorial you will learn about $Topic” def binding = [“TutorialName”:”Groovy”, “Topic”:”Templates”] def engine = new groovy.text.SimpleTemplateEngine() def template = engine.createTemplate(text).make(binding) println template If the above code is executed in groovy, the following output will be shown. Let’s now use the templating feature for an XML file. As a first step let’s add the following code to a file called Student.template. In the following file you will notice that we have not added the actual values for the elements, but placeholders. So $name,$is and $subject are all put as placeholders which will need to replaced at runtime. <Student> <name>${name}</name> <ID>${id}</ID> <subject>${subject}</subject> </Student> Now let’s add our Groovy script code to add the functionality which can be used to replace the above template with actual values. The following things should be noted about the following code. The mapping of the place-holders to actual values is done through a binding and a SimpleTemplateEngine. The binding is a Map with the place-holders as keys and the replacements as the values. import groovy.text.* import java.io.* def file = new File(“D:/Student.template”) def binding = [”name” : ”Joe”, ”id” : 1, ”subject” : ”Physics”] def engine = new SimpleTemplateEngine() def template = engine.createTemplate(file) def writable = template.make(binding) println writable If the above code is executed in groovy, the following output will be shown. From the output it can be seen that the values are successfully replaced in the relevant placeholders. <Student> <name>Joe</name> <ID>1</ID> <subject>Physics</subject> </Student> StreamingTemplateEngine The StreamingTemplateEngine engine is another templating engine available in Groovy. This is kind of equivalent to the SimpleTemplateEngine, but creates the template using writeable closures making it more scalable for large templates. Specifically this template engine can handle strings larger than 64k. Following is an example of how StreamingTemplateEngine are used − def text = ”””This Tutorial is <% out.print TutorialName %> The Topic name is ${TopicName}””” def template = new groovy.text.StreamingTemplateEngine().createTemplate(text) def binding = [TutorialName : “Groovy”, TopicName : “Templates”,] String response = template.make(binding) println(response) If the above code is executed in groovy, the following output will be shown. This Tutorial is Groovy The Topic name is Templates XMLTemplateEngine The XmlTemplateEngine is used in templating scenarios where both the template source and the expected output are intended to be XML. Templates use the normal ${expression} and $variable notations to insert an arbitrary expression into the template. Following is an example of how XMLTemplateEngine is used. Live Demo def binding = [StudentName: ”Joe”, id: 1, subject: ”Physics”] def engine = new groovy.text.XmlTemplateEngine() def text = ””” <document xmlns:gsp=”http://groovy.codehaus.org/2005/gsp”> <Student> <name>${StudentName}</name> <ID>${id}</ID> <subject>${subject}</subject> </Student> </document> ””” def template = engine.createTemplate(text).make(binding) println template.toString() If the above code is executed in groovy, the following output will be shown Joe 1 Physics Print Page Previous Next Advertisements ”;

Groovy – Discussion

Discuss Groovy ”; Previous Next Groovy is an object oriented language which is based on Java platform. Groovy 1.0 was released in January 2, 2007 with Groovy 2.4 as the current major release. Groovy is distributed via the Apache License v 2.0. In this tutorial, we would explain all the fundamentals of Groovy and how to put it into practice. Print Page Previous Next Advertisements ”;

Groovy – Exception Handling

Groovy – Exception Handling ”; Previous Next Exception handling is required in any programming language to handle the runtime errors so that normal flow of the application can be maintained. Exception normally disrupts the normal flow of the application, which is the reason why we need to use Exception handling in our application. Exceptions are broadly classified into the following categories − Checked Exception − The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time. One classical case is the FileNotFoundException. Suppose you had the following codein your application which reads from a file in E drive. class Example { static void main(String[] args) { File file = new File(“E://file.txt”); FileReader fr = new FileReader(file); } } if the File (file.txt) is not there in the E drive then the following exception will be raised. Caught: java.io.FileNotFoundException: E:file.txt (The system cannot find the file specified). java.io.FileNotFoundException: E:file.txt (The system cannot find the file specified). Unchecked Exception − The classes that extend RuntimeException are known as unchecked exceptions, e.g., ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime. One classical case is the ArrayIndexOutOfBoundsException which happens when you try to access an index of an array which is greater than the length of the array. Following is a typical example of this sort of mistake. class Example { static void main(String[] args) { def arr = new int[3]; arr[5] = 5; } } When the above code is executed the following exception will be raised. Caught: java.lang.ArrayIndexOutOfBoundsException: 5 java.lang.ArrayIndexOutOfBoundsException: 5 Error − Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc. These are errors which the program can never recover from and will cause the program to crash. The following diagram shows how the hierarchy of exceptions in Groovy is organized. It’s all based on the hierarchy defined in Java. Catching Exceptions A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. try { //Protected code } catch(ExceptionName e1) { //Catch block } All of your code which could raise an exception is placed in the Protected code block. In the catch block, you can write custom code to handle your exception so that the application can recover from the exception. Let’s look at an example of the similar code we saw above for accessing an array with an index value which is greater than the size of the array. But this time let’s wrap our code in a try/catch block. Live Demo class Example { static void main(String[] args) { try { def arr = new int[3]; arr[5] = 5; } catch(Exception ex) { println(“Catching the exception”); } println(“Let”s move on after the exception”); } } When we run the above program, we will get the following result − Catching the exception Let”s move on after the exception From the above code, we wrap out faulty code in the try block. In the catch block we are just catching our exception and outputting a message that an exception has occurred. Multiple Catch Blocks One can have multiple catch blocks to handle multiple types of exceptions. For each catch block, depending on the type of exception raised you would write code to handle it accordingly. Let’s modify our above code to catch the ArrayIndexOutOfBoundsException specifically. Following is the code snippet. Live Demo class Example { static void main(String[] args) { try { def arr = new int[3]; arr[5] = 5; }catch(ArrayIndexOutOfBoundsException ex) { println(“Catching the Array out of Bounds exception”); }catch(Exception ex) { println(“Catching the exception”); } println(“Let”s move on after the exception”); } } When we run the above program, we will get the following result − Catching the Aray out of Bounds exception Let”s move on after the exception From the above code you can see that the ArrayIndexOutOfBoundsException catch block is caught first because it means the criteria of the exception. Finally Block The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception. Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code. The syntax for this block is given below. try { //Protected code } catch(ExceptionType1 e1) { //Catch block } catch(ExceptionType2 e2) { //Catch block } catch(ExceptionType3 e3) { //Catch block } finally { //The finally block always executes. } Let’s modify our above code and add the finally block of code. Following is the code snippet. class Example { static void main(String[] args) { try { def arr = new int[3]; arr[5] = 5; } catch(ArrayIndexOutOfBoundsException ex) { println(“Catching the Array out of Bounds exception”); }catch(Exception ex) { println(“Catching the exception”); } finally { println(“The final block”); } println(“Let”s move on after the exception”); } } When we run the above program, we will get the following result − Catching the Array out of Bounds exception The final block Let”s move on after the exception Following are the Exception methods available in Groovy − public String getMessage() Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor. public Throwable getCause() Returns the cause of the exception as represented by a Throwable object. public String toString() Returns the name of the class concatenated with the result of getMessage() public void printStackTrace() Prints the result of toString() along with the stack trace to System.err, the error output stream. public StackTraceElement [] getStackTrace() Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack. public Throwable fillInStackTrace() Fills the stack trace of this Throwable object with the current stack trace, adding to

Groovy – Lists

Groovy – Lists ”; Previous Next The List is a structure used to store a collection of data items. In Groovy, the List holds a sequence of object references. Object references in a List occupy a position in the sequence and are distinguished by an integer index. A List literal is presented as a series of objects separated by commas and enclosed in square brackets. To process the data in a list, we must be able to access individual elements. Groovy Lists are indexed using the indexing operator []. List indices start at zero, which refers to the first element. Following are some example of lists − [11, 12, 13, 14] – A list of integer values [‘Angular’, ‘Groovy’, ‘Java’] – A list of Strings [1, 2, [3, 4], 5] – A nested list [‘Groovy’, 21, 2.11] – A heterogeneous list of object references [ ] – An empty list In this chapter, we will discuss the list methods available in Groovy. Sr.No. Methods & Description 1 add() Append the new value to the end of this List. 2 contains() Returns true if this List contains the specified value. 3 get() Returns the element at the specified position in this List. 4 isEmpty() Returns true if this List contains no elements 5 minus() Creates a new List composed of the elements of the original without those specified in the collection. 6 plus() Creates a new List composed of the elements of the original together with those specified in the collection. 7 pop() Removes the last item from this List 8 remove() Removes the element at the specified position in this List. 9 reverse() Create a new List that is the reverse the elements of the original List 10 size() Obtains the number of elements in this List. 11 sort() Returns a sorted copy of the original List. Print Page Previous Next Advertisements ”;

Groovy – Loops

Groovy – Loops ”; Previous Next So far, we have seen statements which have been executed one after the other in a sequential manner. Additionally, statements are provided in Groovy to alter the flow of control in a program’s logic. They are then classified into flow of control statements which we will see in detail. S.No. Statements & Description 1 While Statement The while statement is executed by first evaluating the condition expression (a Boolean value), and if the result is true, then the statements in the while loop are executed. 2 for Statement The for statement is used to iterate through a set of values. 3 for-in Statement The for-in statement is used to iterate through a set of values. Loop Control Statements S.No. Statements & Description 1 Break Statement The break statement is used to alter the flow of control inside loops and switch statements. 2 Continue Statement The continue statement complements the break statement. Its use is restricted to while and for loops. Print Page Previous Next Advertisements ”;