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

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(){

class straightDrive implements Shot{

private Batsman batter;

public void execute(){

class Batsman{

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

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

class BatSimulator{

Shot shot

def play(){

// main - groovy script start

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

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){

    def shutdown(){
for(ShutdownListener l : listeners)

    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()

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 :

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

// 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]

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

// 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) :

Wednesday, November 06, 2013

Fun with Git on Linux

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)

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.


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" />

  <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">
      <checkout url="${project.svn.url}" revision="HEAD" destPath="MyProject" />
<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">  


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.