Friday, September 7, 2012

Say hello to Groovy – Part 2 (Operators & Control Structures)

In my last blog, I gave an introduction to Groovy. We looked at the typical hello world program in Java as well as Groovy to understand how some of the additional features provided by Groovy helps to cut down on a lot of boilerplate code that you would have otherwise written in Java. In this blog, I will concentrate on some of the operators and control structures which are unique to Groovy.

Groovy Truth

Like Java, Groovy supports standard conditional operators in a Boolean expression. In addition to this, any type can be evaluated as a Boolean expression in Groovy. This is possible because Groovy has rules to convert a non-boolean objects to a Boolean value. E.g. In case of string, non-empty strings evaluate to true


Following are some of the rules that you should know: 
1. Empty collection evaluates to false. 
2. Non-zero numbers evaluates to true. 
3. A non-null object reference evaluates to true. 
4. Non-empty Map evaluates to true. 
5. Iterators/enumerators evaluates to false if it has no further elements. 

Operator Overloading

In Java we use the == operator to see if the variables are referring to the same object instance. Groovy overrides == operator on types such as String, Integer, List etc., to check for content equality rather than object equality. To test if two variables are referring to the same object instance in Groovy we use the is () method.





Elvis Operator (?:)


The "Elvis operator" is similar to Java's ternary operator. It can be used for returning a 'sensible default' value if an expression resolves to false or null. E.g. In below snippet, if username is null or empty, “Anonymous” would get printed. 


Safe Navigation Operator (?.)


In Java, it’s a common practice to check for null, before invoking a method on the object to avoid NullPointerException. In Groovy, this is achieved in lesser lines of code using the Safe Navigation operator. The safe navigation operator will simply return null instead of throwing an exception, e.g: In the below code snippet, null would get printed and no NPE will be thrown.



Looping

In addition to all looping constructs available in Java, Groovy provides some extra ways to loop and execute a piece of code. Groovy extends the Integer class with the step (), upto () and times () methods. If we have a List in Groovy we can loop through the items on the list with the each () and eachWithIndex () methods. We will revisit this with examples when I cover closure and collections.


Exception Handling

Groovy doesn’t force you to handle exceptions within the method signature not even for checking exceptions. You are free to choose how and when you handle the exception. The exception is passed on to the calling code until it is handled. E.g. the following is a valid code in Groovy however if you were to write the same code in Java, the compiler would have forced you to handle java.net.MalformedURLException.


Sunday, September 2, 2012

Say hello to Groovy - Part 1

With this blog, I am starting a series on Groovy. Chances are that you are already aware of what Groovy is but in case you are not; Groovy is an object oriented programming language.

Groovy is one of many JVM languages that compiles to bytecode that runs on the JVM. Groovy is also a dynamic language so it’s not statically typed like Java however it has a Java like syntax.It's also a scripting language so you don't necessarily have to compile the groovy code before executing it.


So why would you choose Groovy over Java or other dynamic languages that runs on the JVM like JRuby? While Java like syntax is definitely a plus, Groovy is designed to seamlessly integrate with Java i.e. you can implement a Java interface using Groovy and vice versa.
One other advantage is that Groovy has many modern programming features which were missing in Java e.g. Closure. If you are a Java developer, learning Groovy would be a cakewalk!

 
Getting Started
In order to get started, perform following steps:
  1. Download the latest version of Groovy from http://groovy.codehaus.org/Download.
  2. Once downloaded, extract the content of the zip file into your location of choice e.g. C:\groovy-2.0.1
  3. Create an environment variable called GROOVY_HOME and set it to C:\groovy-2.0.1
  4. Append  %GROOVY_HOME%/bin to the path environment variable.
Once you are done open a command prompt and type groovy - version. If Groovy's version is displayed in the command prompt you are all set to play with it!

 
Walkthrough of Groovy tools

Now that you have Groovy installed, lets look at the tools that you would need to play with it.

groovy - Use this tool to execute groovy source code (.groovy files).  This is typically used for executing Groovy scripts.

groovyc - Use this tool to compile groovy code to Java class file. You would use this tool so that you Groovy source code is not compiled every time before execution.

groovyConsole - This is a minimal editor that you can use to load, type and exceute Groovy code.



 
Typical Hello World

Introduction to any programming language is incomplete without a Hello World program so lets see how a hello world program looks like in Groovy.While we are at it, we will also see how Groovy cuts down on a lot of boilerplate code from Java. Here is how a typical Hello World program would look like in Java.


Here is the list of Groovy features that we are going to leverage :
  1. Default visibility for methods and fields in Groovy is public.
  2. It is a dynamic language so type information is optional.
  3. Semicolon is optional at the end of a statement.
  4. Paranthesis is optional for top level expression.
  5. Groovy provides println which can be used in place of System.out.println. You can use println "Hello World!" inplace of System.out.println("Hello World!");
Once we factor in all the above mentioned features, this is how a Hello World program would look like in Groovy.

Ok. I also mentioned that Groovy is a scripting language so it automatically wraps a script with a default class and main method. So your hello world program in Groovy can actually be a single line of code.



Enhanced Hello World

Now that you got an idea of how Groovy cuts down the boilerplate code and enhances developer productivity, lets look at an enhanced Hello World program.

Here is the enhanced version of Hello World code in Java



lets leverage some of the Groovy features mentioned below and rewrite the same program in Groovy:
  1. Groovy has a feature called Gstring which allows you to write a string containing an expression that can be evaluated. e.g. instead of "Hello "+getName()+"!" you can use something like "Hello $name!"
  2. It also has something called Groovy Bean i.e. if you have a public field or property in a bean class, Groovy automatically generates getter and setter for it. Groovy also provides shortcut to access and set these properties. e.g. in the above example, instead of hello.setName("world") you can use hello.name = "World"
Ok. So this how it will look in Groovy.

 


that's it in this blog. In my next blog i will do a deep dive on some of the Groovy feature.

Friday, August 17, 2012

Introduction to OAuth – Part 2

In this blog we will discuss how OAuth works. Our focus would be on OAuth 2.0. There are many articles on the internet that talks about OAuth 1.0.


How OAuth 2.0 is different from OAuth 1.0

OAuth 1.0 involved certificates so if you were to code for OAuth 1.0 you would have to know about how to sign the requests using signature methods like HMAC-SHA1 or RSA-SHA1 etc. OAuth 2.0 is much simpler. It relies on SSL instead of signatures.

OAuth 1.0 had only one flow for authentication. OAuth 2.0 defines multiple flows or client profiles for handling authentication e.g. web application, user agent and native.

Actors in OAuth 2.0

Following are the important roles in OAuth 2.0

a. Resource Owner – Person whose data/information is to be shared between two applications.

b. Resource Server – Application that hosts user’s data/information.

c. Client Application – Application that needs to access data from the resource server on the resource owner’s behalf.

e.g. let’s assume that I want to use friendfeed to browse the photos that I have uploaded to my Flickr account. In this case, I become a resource owner, Flickr becomes a Resource Server and FriendFeed becomes a Client Application.



Getting Ready for OAuth

Before a client application can start accessing resources on the resource server, it needs to register itself with resource server. This registration is a one time activity and once registered client application gets a client id and secret.

During registration, client application also provides a redirect uri to resource server. This redirect url is used during the OAuth authorization flow.

In the above example, FriendFeed would have registered it with Flickr and obtained client id and secret from Flickr.



OAuth authorization flow

Let’s look at Oauth authorization flow for a web application profile.

Continuing with the above example, assume that I am trying to use firendfeed to access my photos that I have uploaded to my Flickr account. At this time FriendFeed will check if it has an access token in order to get photos from Flickr on my behalf. If access token is not found then FriendFeed would initiate OAuth flow which would typically have following steps.



Step 1: User accesses client application.

Step 2: Client application redirects to resource servers authentication page.

Step 3: Resource server authenticates the user and then obtains user's authorization for the data that client application is trying to obtain from the resource server on the user's behalf.

Step 4: The Resource server generates the authorization code and redirects to client application including authentication code. Resource server uses the redirect url that client application provided during registration.

Step 5: Client application sends a request for access token. Client application includes the client id and secret in this request.

Step 6: The Resource server sends the access token. This access token comes with an expiry date.

Step 7: The Client application accesses the services provided by the resource server to access user’s data as long as access token is not expired.



Here we looked at the flow for web application profile. The flow would vary slightly for other profiles.