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

Monday, March 14, 2016

Getting Started with Apache Spark: Find maximum commits by an author in a git log file

- Install sbt. (scala build tool)
- Install apache-spark.
- Go to the unzipped apache-spark directory and in command line run
sbt assembly

(this takes a while, one may have to increase the memory allocated to run this in config file)

- Clone some git project
  git clone https://github.com/apache/groovy

- Save the log into a text file
  git log > C:\\temp\\log.txt

- Launch spark terminal and execute :

scala> val file = sc.textFile("C:\\temp\\log.txt")
file: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[21] at textFile at <console>:27

scala> val authorLines = file.filter(line => line.contains("Author"))
authorLines: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[22] at filter at <console>:29

scala> var maxAuthorTuple = authorLines.countByValue().maxBy(_._2)
maxAuthorTuple: (String, Long) = (Author: Paul King <paulk@asert.com.au>,2991)

- Verify that maxAuthorTuple has the author who made maximum commits in that branch with the      number of commits.


Tuesday, September 15, 2015

Basic Authentication using Groovy

Here is a very minimal groovy based Basic Authentication Client which can come handy whilst talking to APIs.

def jsonBody = '{"day" : "11", "month" : "03", "year" : "2010", "hour" : "09", "min" : "08", "lat" : "18.9750", "lon" : "72.8258", "tzone" : "5.5", "gender" : "male"}'

new BasicAuthClient(
              userName:"xyzzy",
              password:"ba4d90e133ad76b103fcedcd00ab5681", 
              address:"https://api.vedicrishiastro.com/v1/basic_panchang/"
).doPost(jsonBody)

class BasicAuthClient{

    def userName, password, address, conn
    
    def getAuthHeader(){
        def authHeader = "$userName:$password".getBytes().encodeBase64().toString()
        println(authHeader)
        return authHeader
    }
    
    def getConnection(){
        this.conn = address.toURL().openConnection()
        conn.setDoOutput(true)
        conn.setRequestMethod("POST")
        conn.setRequestProperty("Authorization", "Basic ${getAuthHeader()}")
        return conn
    }
    
    def doPost(body){
        def out = getConnection().getOutputStream(); 
        out.write(body.getBytes()) 
        out.close();
        return getResponse()
    }
    
    def getResponse(){
        def responseCode = conn.getResponseCode();
        println(responseCode)
        def instream = responseCode < 207 ? conn.getInputStream() : conn.getErrorStream()        
        int i = instream.read()
        while (i != -1) {
            print((char)i)
            i = instream.read()
        } 
        instream.close()
        conn.disconnect()
    }
}      


    

Tuesday, June 16, 2015

ConEmu for developer productivity

For the last one and half years, I have been a loyal user of Console 2, an alternative to command prompt on windows. Now, I have moved on to ConEmu for better productivity at workplace. It comes with many settings for customization. What I really love in ConEmu is its split screen support. At times when one is even lazy to shift between tabs/windows. In conjunction with vim, it is a breeze.

Say, you have an executable jar that also produces a log file. To hell with notepad and other UI editors - You could simply split your ConEmu screen to open up two or more console windows and spare one to skim through the output log file (using vim) simultaneously as and when you run the executable through an other.


The only caveat that I see with conEmu is that it eats up a tad bit more of memory than Console2 does (around 40 MB). But I guess I can live with that considering the fact that my laptop is powered with 16 GB of RAM. :)

Wednesday, June 03, 2015

VIM - first things first

Install theme :

https://benaiah41.wordpress.com/2012/01/17/customizing-gvim-in-windows-7/

Append the following lines in ../.vimrc (Startup Settings)

set guifont=Consolas:h11:cDEFAULT
color wombat
set guioptions-=T
set nu
let g:netrw_liststyle=3






















Monday, December 22, 2014

Command Pattern in java/groovy

Command pattern encapsulates a request. A command pattern maybe used whenever there is a Sender, Receiver who communicate via a request (let's call it command). Assume, we simulate the game of cricket via a Simulator class which sends commands  to the Batsman objects to play certain shots. Each shot is a command given by the simulator to a batsman.

interface Shot{
public void execute();
}

class CoverDrive implements Shot{

private Batsman batter;

public void execute(){
batter.playCoverDrive()
}
}

class straightDrive implements Shot{

private Batsman batter;

public void execute(){
batter.playStraightDrive();
}
}

class Batsman{

def playCoverDrive(){
println("Cover drive")
}

def playStraightDrive(){
println("Cover drive")
}
}

class BatSimulator{

Shot shot

def play(){
shot.execute()
}
}

// main - groovy script start

def sachin = new Batsman()
def command = new CoverDrive(batter : sachin)
def simulator = new BatSimulator(shot : command)
simulator.play()

Monday, December 15, 2014

Write a custom event handler in groovy/java

One may write a couple of classes and an interface to achieve event handling without having to implement the Observable/Observer interface. Assume, we have a computer that runs several processes. If it receives a shutdown command, we fire an event to let the running process handle its own clean up method to release resources and halt execution.

interface ShutdownListener{
    public void handle();
}

public class Computer{

    private def listeners = []

    def addShutdownListener(ShutdownListener l){
listeners.add(l)
    }

    def shutdown(){
for(ShutdownListener l : listeners)
l.handle()
    }

    def compute(){ // whatever  }

}

public class Process implements ShutdownListener{

    public void handle(){
// release resources of "this" Process 
// halt execution of self
println("Process ended.");
    }
}

//groovy script start 
def computer = new Computer()
def process = new Process()
computer.addShutdownListener(process)
computer.compute()
computer.shutdown()

Monday, October 20, 2014

Simple way to implement find(select) and collect block closures in java

Languages like ruby, groovy, smalltalk have language constructs for blocks and closures. Java 8 now has feature to evaluate lambda expressions. But here is one simple and straight way to implement the same:

In groovy :

[1, 2, 3, 10, 20, 30].findAll { num -> num > 5 }
=> yields a new list [10, 20, 30]

[ 1, 2, 3, 4 ].collect{ num -> num * num}
=> yields a new list [1, 4, 9, 16]

The above code for those more familiar with the smalltalk syntax will be:

#(1 2 3 10 20 30) select: [ :num | num > 5 ]
==> displays [10, 20, 30]

#( 1 2 3 4 ) collect: [:i | i * i ].
==> displays [1, 4, 9, 16]

In java, the same could be implemented with a set of abstract classes as a collection utility that mandate implementation of method which returns the boolean condition to add or transform the element under iteration :

Find.java
abstract class Find extends ArrayList{ 
    /** let the default constructor worry about iteration **/
    public Find(List list){    
        Iterator it = list.iterator();
        while(it.hasNext()){
            Object element = it.next();        
            if(all(element))           
                this.add(element);         
        }
    }
     
    /** This defines the boolean condition for find/select **/
    public abstract Boolean all(Object obj);
     
}

FindDemo.java
// find all elements in the list that are greater than 5
List list = Arrays.asList(1, 2, 3, 10, 20, 30);
selected = new Find(list) {
    public Boolean all(Object num) {               
        return (int) num > 5;
    }
};
// => yields a new list [10, 20, 30]

Collect.java
abstract class Collect extends ArrayList{  
    /** let the default constructor worry about iteration **/
    public Collect(List list){
        Iterator it = list.iterator();
        while(it.hasNext()){
            Object element = it.next();
            Object transformed = transform(element);
            this.add(transformed);
        }
    }
    /** This defines the transformation logic for collect **/
    public abstract Object transform(Object obj);
}

CollectDemo.java
// collect the squares of all elements in the list
List list = Arrays.asList(1, 2, 3, 4);
collected = new Collect(list) {    
    public Object transform(Object num) {
            return (int) num * (int) num;
    }
};
// => yields a new list [1, 4, 9, 16]

Saturday, October 11, 2014

Gauss Circle Problem

Can do better without two loops :-|


latticePoints = 0
radius = 3.2
mod = int(radius) + 1

def isInCircle(x, y):
    return x*x + y*y <= radius*radius

def calc(x, y):
    global latticePoints
    if x == 0 and y == 0:
        latticePoints = latticePoints + 1
        print((x, y))
    elif x == 0 and y != 0:
        latticePoints = latticePoints + 2
        print((x, y),(x, -y))      
    elif x != 0 and y == 0:
        latticePoints = latticePoints + 2
        print((x, y),(-x, y))      
    else :
        latticePoints = latticePoints + 4
        print((x, y), (-x, -y), (x, -y), (-x, y))          

for i in range(mod) :
    for j in range(mod) :
        if(isInCircle(i,j)):
            calc(i,j)
 
print(latticePoints)





Wednesday, November 06, 2013

Fun with Git

Baby steps : 

1) create an account on github
2) create a git repository. Note down the repo URL.

Install git from terminal : 

sudo apt-get install git

Code Upload :
cd Scripts (or any new folder)
git init (local initialization. creates a local .git folder)
mkdir YourProjectDirectory (and add all source files under it).
git add .
git commit (commits the added source files to the local repository)
git remote add origin yourRepoURL (ex: https://github.com/vamsi-emani/pythonscripts.git)
git pull origin master (to sync with remote copy)
git push origin master (commits all the local changes to remote repository)

To delete a directory: 
git rm -r local-directory-name (recursively remove all local directory files)
git commit (commits to local repo)
git push origin master (commits to remote repo)

Checkout a branch : 
git checkout -b dev_temp origin/test
(creates a local branch dev_temp from remote branch named test)

List local branches only :
git branch

List local and remote branches : 
git branch -a

List all commits on all branches that aren't pushed yet
git log --branches --not --remotes

View commits on a branch (lists out the commits with their hashes)
git log dev_temp

View what's in a specific commit 
git log commit-hash

Remove untracked files
git clean -f --dry-run (to know the damage before doing the action)
git clean -f (to actually delete the untracked files)

Remove untracked files and directories
git clean -f -d

Thursday, July 04, 2013

SVN checkout and Sonar Ant Task Run

The ant script below checks out a java project from a given svn url and runs the downloaded source files against sonar.

Prerequisites: 

SVN Client installed
Included jars on classpath : ant.jar, sonar-ant-task-2.1.jar, svnjavahl.jar, svnClientAdapter.jar, svnant.jar

build.xml (Highlighted portions in red are to be set by user/setup dependent)

<?xml version="1.0" encoding="UTF-8"?>

<project name="Update" basedir="." default="update" xmlns:sonar="antlib:org.sonar.ant">

 <path id="svnant.classpath">
 <fileset dir="lib">    
  <include name="**/*.jar" />
 </fileset>
</path>

  <property name="project.svn.url" value="your-svn-url-of-project" />

  <!-- <taskdef resource="svntask.properties"  /> -->
 <taskdef  name="svn"  classname="org.tigris.subversion.svnant.SvnTask" classpathref="svnant.classpath"/>

  <target name="update">
    <svn>
      <checkout url="${project.svn.url}" revision="HEAD" destPath="MyProject" />
    </svn>
  </target>
   
<property name="sonar.jdbc.url" value="jdbc:h2:tcp://localhost:9092/sonar" />
<property name="sonar.jdbc.username" value="sonar" />
<property name="sonar.jdbc.password" value="sonar" />
<property name="sonar.projectKey" value="org.codehaus.sonar:example-java-ant" />
<property name="sonar.projectName" value="Sonar Sample Project Ant Run" />
<property name="sonar.projectVersion" value="1.0"/>
<property name="sonar.language" value="java" />
<property name="sonar.sources" value="MyProject/src" />
<!-- <property name="sonar.binaries" value="build/*.jar" />
 -->
<property name="sonar.host.url" value="http://localhost:9000" />

<target name="sonar" depends="update">
    <taskdef uri="antlib:org.sonar.ant" resource="org/sonar/ant/antlib.xml" classpathref="svnant.classpath">  
    </taskdef>
   
    <sonar:sonar/>  
</target>

</project>


Friday, November 16, 2012

Kernel Upgrade Issue, Uninstalling 3.6.6 kernel from Ubuntu 12.10

I've upgraded my 12.04 to 12.10 and strangely, I've observed that the kernel version 3.5.x that ships as default with 12.10 has not been upgraded from 3.2.x which I was using in 12.04 LTS version. 

uname -a (for kernel details)

Hence I've tried to do a manual install of latest kernel version 3.6.x, which also failed with an error reporting unmet package dependencies. Not just with the manual kernel upgrade but I've been facing problems with the usual system updates too, that get pushed on a regular basis.

I've tracked this for a while and then realized that I had once made an edit to the default grub configuration file adding an additional "quite splash" line to boost up battery performance. The problem was that after the OS upgrade was done, somehow the simple double quote(") got messed up and was replaced by a smarter double quote (``) which was causing all the errors during my upgrades and updates. I've reverted back the double quotes 

sudo gedit /etc/default/grub

and I have done an update grub. 

sudo update-grub 

..only to realize that 3.6.x, 3.5.x and other older kernel versions were all present and installed but failed to show up because of the grub configuration file error. Moreover, I had realized that 3.6 being the latest didn't work that great at least on MY machine (perhaps because it is not as customized as 3.5 for 12.10) as it was consuming 42W of power as shown on powertop which was too damn high. Hence I've removed the 3.6 kernel using 

sudo apt-get purge linux-image-3.6.*

and I've reverted back to the default 3.5.x kernel that is shipped with 12.10 and everything seems fine now. 

Things I've learnt in the process:
  • It is ideal not to upgrade a kernel version that is more latest than the one shipped with the latest OS version. Even if you wish to do so, compile the kernel separately and then proceed.
  • Installing and uninstalling a kernel. 

Thursday, August 09, 2012

A stupid hack to open short urls blocked by proxy via Launchy

This script will be useful when short urls are blocked by a proxy within a network.

For example:

Lets say the link to an article or blog on the web is this:

LongUrl : http://something.com/somethingelse

Your friend reads the above article and mails the link to you in its shortened form:

ShortUrl : http://bit.ly/s1 or http://t.co/se1

Now when you are on a company network or a protected network, there is a good chance that bit.ly or t.co services are blocked by the proxy though the original site itself (something.com in this case) might not be blocked.

For such cases this silly vbscript can be handy. It basically talks to a longurl.org which lengthens the shortened url and opens it up on the browser.

lurl.vbs

set ws = CreateObject("WScript.Shell")
siteUrl = "http://longurl.org/expand?url=" & Wscript.Arguments.Named("u")

Dim objHttp
Set objHttp = CreateObject("Msxml2.ServerXMLHTTP")
objHttp.Open "GET", siteUrl, False
objHttp.Send
page = objHttp.ResponseText
Set objHttp = Nothing

longUrl = Split(Split(page,"Long URL:")(1),"""")(1)
ws.Run(longUrl)

I have saved the above lurl.vbs file under C:\Temp\Scripts.

From command prompt, running the below command will open up the link in the browser.

lurl /u:your-short-url        


                          
Further more, you can even configure it via the Launchy Runner plugin which makes it more fun.

                                   

Within launchy, typing lurl (tab) followed by site's short url will launch the site directly.

                                 








Wednesday, June 20, 2012

Design Patterns: Factory Method Pattern

/**
* A simple implementation of Factory Method Pattern
* using a real time CricketPlayer example
*/


//Base
public interface CricketPlayer{
    public String play();
}


//Subclass
class Bowler implements CricketPlayer{
    public String  play (){
        return "takes a wicket";
    }
}


//Subclass
class Batsman implements CricketPlayer{
    public String  play (){
        return "hits a six";
    }
}


//Factory class - contains the logic of instatiating players
public class CricketPlayerFactory{
    CricketPlayer player;
   
    public CricketPlayer getPlayerWho(String does){
        if(does.equals("bats"))
            player = new Batsman();
        else if(does.equals("bowls"))
            player = new Bowler();
        return player;              
    }
}


//Factory method implementation
public class FactoryImplementation{
    public static void main(String args){
        //create a factory
        CricketPlayerFactory factory = new CricketPlayerFactory();
        //ask factory to instantiate the player
        CricketPlayer player = factory.getPlayerWho("bats");
        //use the player
        System.out.prinln(player. play ());
    }
}

Design Patterns: Singleton Pattern

/**
* A simple Implementation of a singleton
*/
class MySingleton{
   
    static MySingleton singletonInstance;
   
   //****** instantiation ******


    static MySingleton getInstance(){
        if(singletonInstance == null)
            singletonInstance = new MySingleton();
        return singletonInstance;
    }
   
    private MySingleton(){
        //cannot be called public with new
    }


   //****** logic ******   
    ....
    ....
}


MySingleton.getInstance();


FYI, Points to remember

  • Singletons are bad. 
  • They are just glorified statics and hence against OOP principles. 
  • They should be rarely used. A classic example: for logging purposes.
  • Singletons are hard to unit test.
  • Also bad because it is NEVER a good practice to mix instantiation and logic in a single class. 




Saturday, June 09, 2012

How to know HBOOT version and S-ON or S-OFF on HTC phones


  • Switch off the mobile completely.
  • Hold the volume down button and simultaneously click the power-on button. This will login to the boot menu and display details like this:

    BUZZ PVT SHIP S-ON
    HBOOT-1.01.0002
    MICROP-0622
    TOUCH PANEL-ATMELC03_16ac
    RADIO-3.35.20.10
    Dec  2 2010, 17:14:26

    The first line displays the security flag status. For being able to play around with sudo root access on HTC phones the flag must be turned off (shows S-OFF if turned off). 
  • Click power off button and next hold the volume down button to reboot again into normal menu. 


To be continued.. 





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. 

Friday, May 04, 2012

Setting up Conky & Lua-Widgets

Installing Conky-Lua widget/theme on Ubuntu

1) Install conky and conky-all from Ubuntu Software Center or via apt-get on terminal.

2) Unzip the contents of the tar.gz or zip of Conky/Lua theme submitted by the developer into some folder named Scripts.

Most importantly, the unzipped file will have a conky text file and a .lua file in it.

3) Ensure Nautilus Browser -> View -> Show hidden files option is enabled and create a hidden folder in your /home/Your_Username directory with the name .conky

4) Within the Scripts folder, search for file with .lua extension. This file contains the widget script. Copy the .lua file into the .conky folder.

5) Rename the left over text file in the Scripts folder to a hidden file named .conkyrc and place it in /home/Your_Username directory.


6) Open the .conkyrc file in gedit and edit the portion of the .conkyrc file which refers to the  widget location path i.e the .lua script path. In this case should point to

/home/Your_Username/.conky/someWidgetScript.lua

On terminal run command

conky

which will start the Conky theme/widget.


Installing Multiple Conky-Lua widget/themes on Ubuntu

By default, Running the conky command will invoke the .conkyrc text file at /home/Your_Username location and checks for lua scripts placed in the .conky folder.

In case of setting up multiple widgets you need to have multiple conky text files and multiple lua scripts.

Place all the .lua files in the .conky folder in the /home/Your_Username directory.

Let the text files remain in the Scripts folder but ensure that the configuration path in them points to their corresponding .lua scripts in the .conky folder. (as shown in step 6 above)

In terminal, run

conky -c /home/Your_Username/Scripts/ConkyTextFileScript1
conky -c /home/Your_Username/Scripts/ConkyTextFileScript2
conky -c /home/Your_Username/Scripts/ConkyTextFileScript3

Each of these will take the conky text file path with -c option and individually start the widgets.


PS: You might face issues if any of the above actions, like the path configuration (in step 6) is not done correctly. Also, This requires little bit of scripting knowledge to work your way around. In a nutshell, these are the minimal steps required to setup Conky-Lua Widgets on Ubuntu.




Saturday, April 28, 2012

Power Saving Tips on Ubuntu

If you are running 11.10 and suffering from excessive power consumption on your laptop/netbook, I insist upgradation to 12.04 immediately. In the latest 12.04 LTS release, the kernel bug relating to the excess power consumption has been fixed.

On 11.10, my laptop consumed a whooping 31 to 33 W of power. On 12.04, it has fallen down to 24 W. Further more, I've installed these three utilities which seem to have reduced the power consumption from 24 W to 16 W, which is pretty cool.


1) From Ubuntu software center, search for laptop-mode-tools and install it.


2) Install powertop which helps you assess the power consumption details and configure some of the processes. (sudo powertop on terminal to run it after installation)


3) Install jupiter, a tiny applet that runs on startup, a very useful utility that lets you set the mode to power consumption and also lets you configure the bluetooth and wireless options which typically consume a lot of power.


Installation of jupiter :
sudo add-apt-repository ppa:webupd8team/jupiter
sudo apt-get update
sudo apt-get install jupiter
sudo apt-get install jupiter-support-eee


4) If you are on a hybrid-graphics laptop, you can turn off your graphic card. In my case, this worked like a charm. 

echo OFF | sudo tee /sys/kernel/debug/vgaswitcheroo/switch 


However, the above command is not persistent and needs to run on every startup. 


Standard tips like keeping the brightness low, turning off wireless/bluetooth when not needed would also help.
I have abandoned using Ubuntu 11.10 from the past 3 to 4 months because of its excessive power consumption on my Dell Inspiron. Thanks to Precise Pangolin and these three utilities, I am back on Ubuntu now. :)


Hope this helps some of you battling with power consumption issues on laptops and netbooks running Ubuntu.

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.