Ubuntu insights, Programming in groovy, java, et als!

Showing posts with label groovy. Show all posts
Showing posts with label groovy. Show all posts

Wednesday, May 09, 2012

Currying in Groovy

Currying is a process of transforming a function of n arguments into n partial functions of one argument each.

Although I was acquainted with the math part of it. I found it hard to implement it in code. I
couldn't help but posting Tim Yate's sample snippet to my question on SO about a simple implementation for currying in groovy.


def greet = { greeting, person -> "$greeting $person" }


// This takes a closure and a default parameter
// And returns another closure that only requires the
// missing parameter
def currier = { fn, param ->
  { person1 ->
     fn( param, person1 )
  }
}


// We can then call our currying closure
def hi = currier( greet, 'Hi' )


// And test it out
hi( 'Vamsi' )


Here's an other pointer for doing functional programming in groovy. 

Monday, April 23, 2012

Why Groovy over java?

Some reasons why java developers should consider adapting groovy.

Groovy is married to java 

Groovy's seamless integration with java makes it possible to use all frameworks and libraries available for java, without any hassles regarding language compatibility. Groovy is so much compatible with java that one can merely change the .java extension to .groovy and run it. After all, groovy is just dynamic java with some add-ons and wrappers.

Dynamic typing

Unlike java, groovy does not throw compilation errors on your face. One of the biggest pleasure when compared to java, groovy doesn't impose explicit type casting which is a pain in the butt while programming in java. Groovy is a programmer friendly language and doesn't go out of control as long as the programmer is sure about his own code. It also supports optional typing, the native java syntax can be retained. 

Blocks and closures 

One of the best aspects of groovy is that it provides higher level constructs like blocks and closures found in languages like Smalltalk and Ruby. Block closures are handy powerful features which java lacks.

//To extract the first letter out of each element of a list.
def words = ['animal', 'bird' , 'cat', 'fly', 'dog']
def letters = words.collect{ it[0] }
println letters

//easy iterations
words.eachWithIndex{ word, index ->
    println "$word at $index"
}

The list goes on. Further refer : find{}, findAll{}, sort{}, each{}, contains{} et als, all of which make programming a breeze. 

Reflection in hand

As in smalltalk, Groovy has a concept of metaclass while initializing objects. This metaClass provides wrappers around the native Reflection API of java which enable the programmer to change the behavior of a class at run time.

For example : When compared to java, inspecting the methods of a class at runtime is as simple as :

class Test{
def one = 1
    def getOne(){
        return one
    }
}

println Test.metaClass.methods //prints getOne() and all methods default methods of the class.

Likewise to inspect the properties of a class at runtime, 

println Test.metaClass.properties //prints one and other properties if any

Likewise, injecting a method called getTwo() is as simple as :

Test.metaClass.getTwo = { return 2 }

Sugar Syntax

Besides addition of new language constructs, Perhaps this is one other aspect of groovy which hugely differentiates it with java.

Here I display two good examples that would make groovy an obvious win w.r.t to its sugar syntax.

ex: 1) A program to fetch the contents of a file in java would add up to around 10 - 15 lines. In groovy :

new File('C:\Temp\input.txt').getText()

Or further more, Parsing it is as simple as

new File('C:\Temp\input.txt').eachLine{ line ->
 //parsing logic
}

ex: 2) Given a url, to read the contents of a webpage, in java there is all this crap of opening streams, buffered readers and piping the contents, handling the exceptions etc. In groovy it is as simple as

'http://nerdysermons.blogspot.in'.toUrl().text

Further more...

Groovy has excellent wrappers around basic java functionalities. For example: With SwingBuilder, building swing UIs becomes darn simple.

For example: To built a swing application with a click me button and text area that prints hello message upon button click, a java program for the same would extend to more around 30 - 40 lines of code with initialization, building UIs, writing an actionListener etc. In groovy, this four liner script would suffice. 



new groovy.swing.SwingBuilder().edt{
    frame(show:true, size:[200,270]){
    panel(){
        button(label:'Click Me', actionPerformed :{ta.setText('Hello')})
        ta = textArea(columns:20, rows : 10)
        }
    }
}



Another great feature of groovy is its ability to build, create and parse XMLs with its XmlParser and XmlSlurper facilties. Some other include inbuilt assertions, GPath expressions,    String interpolations, etc.

I can go on like this for some time. This post is an introduction to depict groovy goodness comparing it to java which is strict and verbose. The more emphasis w.r.t the groovy vs java argument is on writing less code which possesses the java-ish flavor but is a lot elegant.



Wednesday, April 04, 2012

Redirecting log4j and Print streams to Custom Console

This is a custom JTextArea that I've coded for that can redirect and display all the print streams onto it including apache's log4j statements.



class MyConsole {
static outArea, consoleScroll, consoleTab

static log = Logger.getLogger(MyConsole.class)


//redirect the current println and err streams onto custom Stream 


static setUpStreams(){
outArea = JTextArea(10,100)
System.setErr(new PrintStream(new MyStream(outArea)));
System.setOut(new PrintStream(new  MyStream (outArea)));
WriterAppender logAppender = new WriterAppender(new PatternLayout(), new    MyStream (outArea));


Logger.getRootLogger().addAppender(logAppender);
}

public MyConsole(){ 

      setUpStreams()
}

}

//custom stream to which the standard streams are redirected
public class  MyStream  extends OutputStream {
JTextArea ta;
def str = ''
def buffer = []


MyStream (JTextArea t) {
super();
ta = t;
}

//detects \n and stores the line in a buffer and then prints the whole line..

public synchronized void write(int i) {

buffer.add(Character.toString((char)i))
if(buffer.last()=='\n'){
buffer.each{
str = str + Character.toString((char)it);
}

ta.append(str)
str = ''
buffer.clear()
}


//ta.append(Character.toString((char)i));

}

public synchronized void write(char[] buf, int off, int len) {
String s = new String(buf, off, len);
ta.append(s);

}
}



PS : I tried to keep the java-ish syntax alive in the snippet. Albeit that I guess I might have resorted to groovy's sugar syntax in a couple of places. Please make the changes accordingly. 

Monday, January 23, 2012

Find Source code Line Numbers of Methods at Runtime


Comparing a source file and a runtime equivalent object of the class, here is a ten liner groovy script that determines the line numbers of every method inside a class. A plausible approach to do this in java is is to throw a stacktrace explicitly wherever needed and examine it to determine the line number at the point of execution. This I find is too clumsy a way. One can also take an other approach by parsing the source code file, creating a tree node structure and manipulate it but then the problem with this approach is that one has to reinvent the whole wheel again.

Groovy's dynamism comes to rescue here exposing the runtime object to the programmer during execution. At runtime, one can inspect an object, study its methods and properties and manipulate them as per the need. This can also be done in java using the Reflection API but I find it too monstrous and verbose. I resort to groovy instead. Here's the ten liner script for the same.

//supply the source file path, the only input to the script
def sourceFilePath = 'C:\\Temp\\GroovyUtils\\Sample.groovy'

//a map that stores method names vs line numbers as key val pairs
def methodToLineMap = [:]

//find all the methods of the Sample class and assign default line number as 0 first.
def listOfMethods = new Sample().metaClass.methods*
listOfMethods .name.sort().unique().each{
    methodToLineMap.put(it,0)
}


//parse src file to find the line numbers of methods & store line number in the methodMap
def idx = 0
new File(sourceFilePath).eachLine{ line ->
    idx++
    methodToLineMap.keySet().each{method ->
        if(line.contains(method)){
            methodToLineMap[method] = idx
        }
    }
}

//print the elements of method vs line number map
methodToLineMap.each{
    if(it.value!=0)
        println it
}

PS : You can also supply a java source code file (in sourceFilePath) to find out the line numbers of the java class's methods but ensure that the .class file is on the classpath while running the script.

Tuesday, November 15, 2011

Count the Lines of Code in Your Project

I was searching through eclipse if there was an option somewhere within the IDE that could count the total lines of code in my project. After 5 min of Google struggle, I got to know that I need to install a metrics plugin to be able to do so. Reluctant to install any additional plugin, I resorted to groovy, spending an equivalent 5 min of time for this piece of code that counts the total number of lines in all the files within a directory at any depth.

Run the below script with dirPath variable pointing to your project base and addup comma seperated extensions in the filterFileExtensions variable list to specify the filetypes you wish to index , as in java, groovy or any text rendering file extensions like txt, html, etc. 

//------------------- Start Groovy Script --------------->


def filterFileExtensions = ["groovy", "java"] 
def dirPath = 'C:\\VKWorks\\Sampleproject'


def base = new File(dirPath)
def obj = new FileUtil(list:filterFileExtensions)
obj.recurseCountCodeLines(base)
obj.printResult()
//------------------- End Groovy Script --------------->


class FileUtil{
def lineCount = 0
def filesProcessed = 0
def list 


def recurseCountCodeLines(file){
    if(file.isDirectory()){
        file.listFiles().each{recurseCountCodeLines(it)}
    }


    else{
    def fileExtn = file.getName().tokenize(".").last()
    if(list.contains(fileExtn)){
        println "processing file $file"
            file.getText().eachLine{ line ->
            def isCommentedCode = line.startsWith("/") ||
                                  line.startsWith("*")                      
                if(line.size()>0 && !isCommentedCode)
                    lineCount++
            }
            filesProcessed ++
        }
    }
}
    
def printResult(){
    println "---------------------------------"
    println "files processed : $filesProcessed "
    println "Code line count : $lineCount"
    println "---------------------------------"
}
}



PS on performance: 12,000 lines of code in 150 odd files within various depths of the specified directory were retrieved in less than a second. 



Wednesday, September 21, 2011

Groovy Based RSS Reader - Intro


A desktop application with the help of which a user can keep track of his favorite blogs or the frequently visited websites.
Pre-requisite to be able to work with:
The website/blog should necessarily have an option for RSS feed subscription.
Rough Ideas/Steps involved :
1) Fetch the URL of the website/blog from the user as input.
2) Search the metatags of the page for existence of an rss feed.
3) If an rss feed for the website/blog exists, fetch the rss content from the feed URL, parse it and perform the display logic.
4) On exit, save state of UI i.e of all the blogs subscribed. On reopen, update feeds.
Genuinely started with the aim to target bloggers i.e users of blogspot/wordpress and other famous blog hosting sites. Should be in a position to extend the functionality to all websites that provide for an RSS subscription.

Monday, September 19, 2011

Serializing objects in Groovy

Never came across a more sexier way to serialize objects. Thanks to groovy goodness.


def map1 = ['1':'one']
def map2 = ['2':'two']

def file = new File("C:/serializedObjects.txt")

file.withObjectOutputStream { out ->
    out << map1
    out << map2          
}
                     
file.withObjectInputStream(getClass().classLoader){ ois ->
    ois.eachObject{
        println it                  
    }
}      

Monday, August 22, 2011

Retrieve the RSS Feed URL of a Webpage

/* A dirty code tweak that can search the meta tags
* of a webpage for its rss feed url.
* If a feed exists for the page,
* the rss feed link portion of the page source
* will be extracted using regex.
*/

def getRSSFeedURLFor(String urlStr){
def url = urlStr.toURL()
def result = []
def str
def lookForStart = '''<link rel="alternate"'''
def lookForEnd = '''>\n'''

url.eachLine {
if(it.contains("RSS"))
result << it + "\n"
}

result.each{
if(it.contains(lookForStart)) {
strtIdx = it.indexOf(lookForStart)
lastIdx = (it.indexOf(lookForEnd)+2)
str = it.substring(strtIdx,lastIdx)
}
}

str = str.replaceAll(/(.*)(href.+)"(.*)"(.*)\n/,'$3')
str = str.trim()
return str
}

def urlStr = "http://www.ashes-phoenix.blogspot.com"
def rssURL = getRSSFeedURLFor(urlStr).toURL()
println rssURL

PS: For most of the standard websites, if an RSS feed exists for the page, it will be specified in one of the metatags of the page source that looks like:

<link rel = "alternate" type=atom/application/rss+xml href=''...>

The logic lies in extracting the link within the href attribute of this tag which is actually the rss feed of the page we are trying to retrieve


Friday, August 19, 2011

Build a Binary Tree & Perform an Inorder traversal



/*
* A simple groovy implementation to create a Binary Tree
* and to perform inorder traversal
*/

class Node{

    Node left, right
    int data
   
    Node(data){
        this.data = data
        left = null
        right = null
    }
}


class BTree{

    static def insert(Node node, val){
      if(val < node.data){
          if(node.left == null){
              node.left = new Node(val)
              println "inserting $val to the left of $node.data"
          }
         
          else insert(node.left, val)
      }
     
      else if(val > node.data){
          if(node.right == null){
              node.right = new Node(val)
              println "inserting $val to the right of $node.data"
          }
         
          else insert(node.right, val)
      }
     
    }
   
    //left, root, right
    static def printInOrder(Node node){
        if(node == null) return
       
        else{
            printInOrder(node.left)
            println node.data
            printInOrder(node.right)
        }
    }
}

//Shift to main if you aren't running this as a groovy script
def root = new Node(25)
BTree.insert(root, 10)
BTree.insert(root, 30)
BTree.insert(root, 24)
BTree.insert(root, 299)
BTree.insert(root, 266)
BTree.insert(root, 121)
BTree.insert(root, 920)

//Inorder traversal of the entered elements
BTree.printInOrder(root)