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

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. 

Tuesday, April 03, 2012

Creating Windows Shortcuts for your Application Programatically

Here is a 10 liner vbscript that can dump shortcuts for your application on desktop and All Programs menu in windows.


set WshShell = WScript.CreateObject("WScript.Shell" )
WinDir = WshShell.ExpandEnvironmentStrings("%WinDir%")

pathToDesktop = WshShell.SpecialFolders("Desktop")
set desktopShortcut = WshShell.CreateShortcut(pathToDesktop & "\MyApp.lnk")
desktopShortcut.TargetPath = Wscript.Arguments.Named("target")
desktopShortcut.WindowStyle = 1
desktopShortcut.IconLocation = WinDir & "\system32\SHELL32.dll,43"
desktopShortcut.Save

pathToStartMenu = WshShell.SpecialFolders("StartMenu")
set startMenuShortcut = WshShell.CreateShortcut(pathToStartMenu & "\Programs\MyApp.lnk")
startMenuShortcut.TargetPath = Wscript.Arguments.Named("target")
startMenuShortcut.WindowStyle = 1
startMenuShortcut.IconLocation = WinDir & "\system32\SHELL32.dll,43"
startMenuShortcut.Save





Execution from Command Line: 

cd to the directory where the above script is saved as mkshortcut.vbs.

Here I create a shortcut to a directory F:\Temp or any other file (even batch files or exe files which launch your application).


mkshortcut /target:"F:/temp"


The above command will create a shortcut called MyApp.lnk on your start menu >> Programs and on Desktop.

Execution from groovy program :

Prefix the above command with "cmd /c" and execute.

"cmd /c $command".execute() where in the command variable stores the mkshortcut line above as string.

Like wise, the same can also be extended to java using the Process Object.