Skip to main content

Posts

Showing posts with the label groovy

Slashy strings in Groovy

Groovy has done a great job of enhancing Java Strings. It offers a lot of features like String interpolation with GStrings, triple quoted Strings, multi-line Strings, and slashy Strings. In this post I will talk about slashy Strings in Groovy. But before doing that let us see how we represent a regular expression in Java. Let's say I have a list of fully qualified file names and I want to match all files in my 'c:\tmp' directory. I would create a String to represent my regex in Java like this: String exp = "C:\\\\tmp\\\\.*" The four '\' are needed because '\' is a meta character in regular expressions, so we need to represent a '\' as a '\\'. Because a '\' is used for escaping special characters in Java, we need to represent '\\' as '\\\\'. Wow doesn't this look cumbersome. Well, this is not just one case. Regular expressions make use of the '\' character for special classes. Everytime we want to ...

Create mock objects with metaprogramming

We usually create mock objects in our test suites for those classes which communicate with some external entity that we cannot (or do not care to) setup in our test cases. However, mocking is possible only when we have used dependency injection properly. If we have classes that instantiate their own dependencies then we cannot mock the dependencies. Sometimes our mock solutions may also be time intensive at runtime. I will explain this later in the post. One solution (the correct one) is to refactor the code and use proper dependency injection to allow classes be be mocked. However, when we have a huge code base of non DI code, which cannot all be changed at a time, then we just have to make so with fewer unit tests. But all is not lost. If we use a dynamic language like Groovy to write the test cases then we can use metaprogramming to change a classes methods at runtime instead of creating mock classes. I am building a command line Twitter client in Groovy. I have a class called Frie...

Injecting methods in Groovy with ExpandoMetaClass

I am writing a Twitter client in Groovy. One of the things I want to do is create a thread which will poll Twitter for new updates at regular intervals, and go to sleep when it is not doing anything. The way we write such code is to invoke the sleep method with the number of milliseconds to sleep. To sleep for 2 minutes, I would write: Thread.sleep(1000 * 60 * 2) This code is fine, but not very readable. I would have preferred to write something like this: Thread.sleep(2.minutes()) This is not possible in Java, but it is in Groovy. In Groovy we can inject methods into a class at runtime. This is done using the class' ExpandoMetaClass, as the example below shows. Integer.metaClass.seconds = {return delegate * 1000} Integer.metaClass.minutes = {return delegate * 1000 * 60} Integer.metaClass.hours = {return delegate * 1000 * 60 * 60} //test assert 3.seconds() == 1000 * 3 assert 5.minutes() == 1000 * 60 * 5 assert 4.hours() == 1000 * 60 * 60 * 4 The above code gets Integer's metacl...

Closures in lieu of inner classes in Groovy

Groovy does not support inner classes, at least not in version 1.6 . Having done Java coding for many years, I have become accustomed to using inner classes to encapsulate small related functionality, especially when it is needed for callbacks or some sort of configuration. Now that I am learning Groovy, and writing a Twitter client, I needed to use inner classes, only to find out that Groovy does not support them. However, we can use closures and maps to simulate inner classes in Groovy. Before I explain this technique, I must say that it is simply a workaround, and at least in my opinion a not-so-good solution. For this example I will show how I implemented a Jetty Handler using closures instead of an anonymous inner class. Jetty is a Java web server which supports Servlets and JSP's. I often use Jetty in my unit tests, because it can be started in-memory from an API call. Jetty can be configured in code with handlers, so that it will use these handlers to service a web request. ...

Groovy beans

A typical Java Bean is a Java class which is serializable, has a public no-arg constructor, private attributes, and getter/setter methods. I'd say this is a lot of stuff for a simple pojo. Groovy beans did to pojo's what Java could not. They are actually simple. A typical Groovy bean needs to implement java.io.Serializable and add properties to it. We do not need to add any getters/setters, they are added automatically for us. Here is a simple Groovy bean. class Customer implements java.io.Serializable { String firstName //will be a private attribute in the bytecode String lastName //will be a private attribute def middleInitial //beans can even contain dynamic properties } See.... Groovy beans do not have any getters or setters, and you will also have noticed that the fields are not private. Even though the source does not contain getter/setter methods and private attributes, the bytecode does. When this bean is converted into bytecode all attributes which do not have an a...

Control structures in Groovy

To control program flow in Groovy we can use all control structures available in Java, but with additional power. In Java, branching statements like 'if', and 'while' accept an expression which evaluates to a boolean value. We cannot use an object where a boolean is required. Groovy, on the other hand has the concept of Groovy truth, which coerces non boolean values into boolean values. Thus statement like these are perfectly valid in Groovy. List list = ['apples'] if(list) { println 'This list is not empty' } Here the list object evaluates to a boolean value. Any non empty list will evaluate to true. This article explains coercion rules for the Groovy truth. Groovy truth allows us to use non booleans inside conditionals. It evaluates objects to their (truth) boolean values. With Groovy truth we can use booleans, Strings, GStrings, List, Map, Numbers, and any arbitrary object where a boolean is expected. Groovy also gives greater power to switch statem...

Groovy Maps

Using Maps in Groovy is much simpler than in Java. Some key differences are: Map declaration and instantiation are simpler Elements of a Map can be accessed either using the bean style or array style Iterating across Maps is far less verbose in Groovy than in Java The code sample below is self explanatory //Declaring and instantiating a Map def emptyMap = [:] //Populating a Map //Notice that the keys which are strings are not //enclosed within quotes def population = [Estonia:1299371, Finland:5250275, Honduras:7792854, HongKong:7055071] //Non string keys must be enclosed in () def numbers = [(Integer.valueOf("1")):"One", (Integer.valueOf("2")):"Two"] //Accessing Map elements //Maps can be accessed using bean style and //array style notations respectively println "Estonia population: " + population.Estonia println "Finland population: " + populatio...

Groovy types

Java is a statically typed language , which means we have to declare the type of a variable at compile time. Python is dynamically typed. which means that references can never to bound to types at compile time. Groovy on the other hand has optional typing. What this means is Groovy references can be statically typed like in Java, or dynamically typed like in Python. String staticStr = new String("this is a statically typed String"); staticStr = 8; println """The type of staticStr is: ${staticStr.class.getName()} """ println """It's value is: $staticStr""" The output form running the above program is: String staticStr = new String("this is a statically typed String"); staticStr = 8; println """The type of staticStr is: ${staticStr.class.getName()} """ println """It's value is: $staticStr""" As you can see, staticStr remains a string even a...

Groovy Ranges

Groovy Collections offer us a class in addition to Java Collections, called Range. Range is a subclass of java.util.List and is used for creating lists of sequential values. Some ranges can be: 1..3 a..d Notice that we use the .. operator to create a range. However ranges are not limited to numbers and characters. Any object which implements the methods compareTo(), next(), and previous() can be used in a Range. Ranges typically have a left and right border, and they can be either inclusive (containing border elements) or exclusive (sans the right border element). Ranges are usually used to extract a subset of elements from a list or used in switch statements to match a range of cases together. The code below is self explanatory: //A simple Groovy Range def inclusiveRange = 1..10 println 'The size of inclusiveRange is: ' + inclusiveRange.size() //This range does not include the right border element def exclusiveRange = 1.. 0} Output from running the above program: The size of ...

Groovy closures

Java does not have closures , but till sometime back it was a highly debated topic on various Java forums. Groovy is a language which compiles to Java bytecode and does have closures. Closures are very prominent in many programming languages, such as Groovy, Python, Ruby, Javascript, and probably many more. So what are closures? A closure is a block of code which can be passed to a function. Closures in Groovy are normal objects, which do not have any visible state. Closures are most often used in iteration logic and resource handling. Whenever we iterate across a collection, we normally do so to perform some logic on all or some members of the collection. Closures make it easy to represent that logic in a very concise and readable way. Closures can also be used for resource handling. Very often we open a file resource do something with the file (read from it, write to it, or both), and then close the file. The first and last parts, that is opening and closing the file are really plumb...

Groovy Lists

In a previous post I talked about Groovy numbers. In this post we discuss Lists in Groovy. One thing that strikes me is the use of operators in Groovy. Groovy has reduced verbosity wherever possible with the use of operators. We create a List in Java like this: List list = new ArrayList (); and in Groovy like this: def list = [] Why do you think we do not use generics in Groovy? You can reply on Twitter . Groovy allows us to apply several operators like +, -, *, and << //Lets create an empty list. Notice, we can create a list with the [] //operator def aList = [] //size is also an attribute in Lists (we cannot invoke methods //without the ()) println 'size if aList is: ' + aList.size println 'Lists created with the [] operator are of type: ' + aList.class.getName() //What if I want a linked list? def lList = [] as LinkedList println 'lList is of type: ' + lList.class.getName() //We can also create a LinkedList by specifically instantiating it //li...

Groovy numbers

I was very pleasantly surprised when I learned how to work with numbers in Groovy. The first difference between Groovy and Java (while dealing with numbers) is that in Groovy numbers are always objects. There are no primitive numbers like in Java. This may have the disadvantage of increased memory usage, but it also has the advantage that working with large numbers is much easier. If you have tried doing high precision calculations or working with really large numbers in Java, then you know how difficult it is to work with BigDecimal and BigInteger to perform calculations. We have to call methods instead of using operators. Let's see this with a small example. If I want to print the value of Long.MAX_VALUE * 2, I have to use BigInteger and then invoke it's multiply method as shown in the example below: System.out.println(Long.MAX_VALUE * 2); //Incorrect: prints -2 //The right way to work with large numbers in Java BigInteger bi1 = new BigInteger("9223372036854775807")...

String handling in Groovy

This blog post shows through a simple example, how to manage strings in Groovy. Here are a few things which are different in Groovy strings: Groovy strings can be enclosed within single quotes: 'this is a string' double quotes: "this is a string" triple (single or double) quotes: '''this is a string''' and """so is this""" Groovy has something called GStrings which uses replacement variables Groovy makes it easier to use strings in regular expressions The == operator in Groovy actually invokes the equals() method Groovy overloads the +, -, and * operators in Strings With these concepts in mind the example below should be self explanatory. Try running this example yourself and see the output. After that change the source and see how it affects the output. //Groovy allows single quoted strings def string1 = 'hello world' println string1 //Groovy allows double quoted strings (GStrings have to be double quoted)...

Learning Groovy

I have started learning the Groovy programming language . Looks like dynamic languages are getting really popular these days, and keeping up with my resolution to learn a couple of programming languages this year, I have started learning Groovy. In short Groovy is a dynamic language which fully interacts with Java. Groovy can invoke Java objects, in fact it itself compiles to bytecode, so Java objects can also invoke Groovy. In the next few posts I will share what I learn and my notes comparing Groovy with Java. Let's start with a HelloWorld in Groovy println 'Hello World' That's it. You do not need to enclose your HelloWorld in a class or the main method. This is really cool if you just want to create a simple script file to do something quickly for you. But how does this get compiled to Java bytecode. Java always needs a class and methods to hold code. Well in my case the Groovy plugin in Eclipse automatically compiled the above code and put it in a class with the sa...

Getting interested in polyglot programming

From the last few days I have started learning Groovy by listening to the Groovy series podcasts . While listening to the podcast on numbers ( attached_code ), I couldn't help smiling when I saw this (line 42 in the attached code): assert 1/2 == 0.5 Yes 1/2 is actually 0.5 in Groovy. Isn't that awesome :-) We all know what we get when we write this code in Java: System.out.println("1/2 = " + 1/2); A few other things I found interesting about Groovy numbers are: def bigDecimalObj = 5.12345 assert bigDecimalObj.class.name == 'java.math.BigDecimal' Groovy treats all floating point numbers as BigDecimal (there are exceptions, but I will not get into that here). We all know how difficult it is to implement high precision calculations in Java. We cannot use double, because we may lose precision in calculations involving double. The alternative of using BigDecimal results in unreadable code. However, Groovy can be compiled to bytecode and can coexist with Java. So n...