Tuesday, 17 December 2013

Change Mouse Icon in XFCE 4

Just installed brand new Debian Wheezy x86_64 with XFCE 4 on my 2010 model netbook having an Intel Atom processor. XFCE is fast and is less resource hungry. As it's the case with much of the distros, the UI themes are not so very eye-candy. So, in the process of making it look more beautiful, I got stuck with not being able to change the mouse pointer icon. The interesting thing is that rest of the mouse icon type changes. Also when I am within Firefox, I can see the updated icon. Everywhere else I get the default adwaita icon. Fixing this is simple.
cd /usr/share/icons     # cd to global icons dir
sudo rm default         # remove if default exists
# create a symlink setting oxy-neon (which is the name of the folder containing mouse icon theme) as the default mouse theme
sudo ln -s oxy-neon default
Choose Mouse option from Applications Menu -> Settings and select the Theme tab and choose Default as the pointer. Logout and the new mouse theme appears.

Sunday, 8 December 2013

Running LFE in Windows

Building LFE (Lisp Flavoured Erlang) does not seem to work in Windows. Running make gives the following error.
rebar was unexpected at this time.
make: *** [compile] Error 255
However, if you have access to a GNU/Linux system, you can build it there, get the .beam files inside the ebin directory over to Windows, which can be loaded by the EVM running on Windows.
Say you placed it under C:\lfe-ebin, open the Erlang shell and run the following
1> cd("c:/lfe-bin").
2> lfe_shell:start().
LFE Shell V5.10.3 (abort with ^G)

Thursday, 5 December 2013

Fun with FizzBuzz

Here is my shortest Groovy version of FizzBuzz in 62 characters and legible.
JavaScript version in 66 characters, but a bit convoluted.

Sunday, 1 December 2013

Groovy Parallel and Async Tasks with GPars

Groovy is a very pragmatic language. It keeps ceremony to the minimum while taking advantage of the mighty JVM and the Java platform. The GPars library is a convenient way to run computations in parallel, async or concurrent. The same thing can be achieved to an extend with plain Java with the java.util.concurrent.* classes. An article by Edgardo Hernandez demonstrates the usage with Java. Let's use Groovy and GPars to do something similar.
import groovyx.gpars.GParsPool

public class Task {
    def compute(int msg) {
        String str = "";
        long begTest = new java.util.Date().getTime();
        System.out.println("start - Task "+ msg);
        try {
            for(int i = 0; i < 20000; i++)
                str = str + 't';
        } catch (InterruptedException e) {}
        Double secs = new Double((new java.util.Date().getTime() - begTest)*0.001);
        System.out.println("run time " + secs + " secs");
        return msg;

final def task = new Task()
def seq = {
    println "sequential"
    long b = new Date().getTime()
    (1..5).each {
        long e = new Date().getTime()
        println e-b

println "\nparallel"
GParsPool.withPool { //pool size will be automatically computed (if nothing is specified).
    long b = new Date().getTime()
    (1..5).eachParallel { // executes each block in parallel and statement within the block sequentially.
        long e = new Date().getTime()
        println e-b

println "\nasync (demo)"
long start = new Date().getTime()
// Say we have few tasks that needs to be computed asynchronously while doing other computations.
def a = {task.compute(1)} // define the tasks in a block
def b = {task.compute(2)}
def c = {task.compute(3)}
def d = {task.compute(4)}
def e = {task.compute(5)}
def results = GParsPool.withPool {
    [a,b,c,d,e]*.callAsync() // perform the tasks in the background
// continue with other tasks..
results*.get() // now we need the results to continue further. Get the result (if not done yet, it waits till done).
// do further computation with the obtained results..
long stop = new Date().getTime()
println stop-start
This can be run using groovyConsole. GPars must be in the classpath or included using grapes. In my test system having dual cores, the time taken are around 10375ms, 6578ms, 6234ms for sequential, parallel, and async tasks respectively. In a single core atom processor the average time for 3 runs are as 13792ms, 10771ms and 9078ms respectively.

Saturday, 9 November 2013

Erlang: Anonymous Recursive Function

The Erlang shell evaluates expressions. Calling an anonymous function by itself is a bit tricky. The easy way to do it is to pass in the reference to the function as one of its arguments. Variable binding by pattern matching happens only after a function gets defined. So we cannot call the function by the variable name from within itself.
In the example the D(L) displays the elements in the list L.
1> D = fun(F, []) -> ok;
1>        (F, [H|T]) -> io:format("~p~n", [H]), F(F,T) end.

2> D(D, [a,b,c]).                               
If the binding takes place before the function definition, we could have written like
1> G = fun([]) -> ok;
1>        ([H|T]) -> io:format("~p~n", [H]), G(T) end.
* 2: variable 'G' is unbound
but, we can see that it gives an error. This is similar to a fixed-point combinator like a Y combinator.

Wednesday, 6 November 2013

Erlang: Reading a Line of Integers from stdin

There are various functions that can be used for reading from standard input. I have a line of integers separated by a space in between. There can be 1000 to 10,000 or more numbers in a line. I want to read them all and use them for further processing. I mainly thought of two ways, one is to read individual integers each and build a list. The other method is read the whole line in one go as a string, split the string delimited by space which gives a list of strings and convert each string element to an integer. Now the question is which of the two would be faster?
#!/usr/bin/env escript

% Read input as an integer
read_input(Inp) ->
    case io:fread("", "~d") of
        eof ->
            % display the list
            io:format("~p~n", [lists:reverse(Inp)]),
        {ok, [N]} ->
        _ -> read_input(Inp)

split(S, D) ->
    re:split(S, D, [{return,list}]).

%% Read input as a string 
read_input() ->
    case io:get_line("") of
        eof ->
        N ->
            % display the list
            L = lists:map(fun(X) -> list_to_integer(X) end, split(string:strip(N--"\n"), " ")),
            io:format("~p~n", [L])

main(_) ->
I am testing this using escript without -mode(compile) which interprets the code.
The lowest time the read_input([]) function took to read and display a line of 1000 integers (around 7 digits each) was 2.235s and read_input() took only 0.750s. The average for 7 runs were 2.256s and 0.77s respectively. In the first method we can see that the list is created by appending elements to the head which is a really fast operation. Which shows that it is better to reduce the number IO calls and get the input as a chuck.
With 10,000 integers, the first function takes 2m28.625s and the second one takes only 1.875s.
NB: Reading in as string can be slow in other programming languages. In Erlang strings are represented as a list of integers.

Friday, 1 November 2013

Case Insensitive Regex in Erlang

Case insensitive matches with regular expression can be done by specifying caseless as one of the options.
1> S = "Hi there, hello there. Hello world!".
"Hi there, hello there. Hello world!"

2> re:run(S, "hello", [global, caseless]).

3> re:run(S, "hello", [global]).

4> re:run(S, "hello", []).

Thursday, 31 October 2013

Erlang: Truncate a Floating Point Number to N Decimal Places

An Erlang function to truncate a floating point number to N decimal places ignoring trailing zeros.

%% Truncates a floating point number F to N decimal places ignoring trailing zeros.
-spec trunc(float()|integer(), integer()) -> float().
trunc(F, N) ->
    Prec = math:pow(10, N),
1> c(ql).

2> ql:trunc(3.1415926525, 4).

3> ql:trunc(3.1400, 4).      

4> ql:trunc(3.0, 4).   

5> ql:trunc(3, 4).  

Tuesday, 29 October 2013

Pipe Input from stdin to an Erlang Program

Below is an Erlang program which read integers from the standard input and outputs them in reverse order. escript provides scripting support for short Erlang programs which can also take command line arguments.
#!/usr/bin/env escript

r(L) ->
    case io:fread("", "~d") of
        eof ->
            io:format("Reverse List: ~p~n", [L]),
        {ok, [N]} ->

main(_) -> r([]).
I have inputs in a file in.txt.
To pass it the Erlang program we can use the pipe | operator with cat.
cat in.txt | escript hr.erl
This will produce the output
Reverse List: [2,1,0,6,5,4]
It is a normal practice to use the redirection operator < to send input as stdin taken from a file. But for some reasons, it's not working as intended with Erlang programs. The above program does not terminate if used with the redirection operator. It's the same case when using the command erl -noshell -s hr main < in.txt with exported module and function main/0. Of course, Erlang is not meant to be used like this. But still, it would be nice if we could. So finally pipe to the rescue. Instead of redirection, use pipe to send in input, which works correctly.

Sunday, 27 October 2013

Erlang List Comprehension with Multiple Generators

I was a bit lost with the permutation example from the Erlang docs. The post by Peter Miller helped. Anyway, here is my explanation on its working.

Generate permutations of all elements in a list.
perms([]) -> [[]];
perms(L)  -> [[H|T] || H <- L, T <- perms(L -- [H])].
Let's say it's in a module named test. Compile and load it. Call it will the list [1,2,3].
1> test:perms([1,2,3]).
To understand this let us look at list comprehension. Single generators are straight forward.
2> [X || X <- lists:seq(1, 5)].
Read it as, X such that X is generated from a list with sequence 1 to 5. Let us consider list comprehension with multiple generators.
3> [{X, Y} || X <- [1,2,3], Y <- [10,11,12]].
Here we are constructing a tuple {X, Y} such that X is generated from list [1,2,3] and Y is generated from the list [10,11,12]. We can see the pairing from the generated list of tuples. It takes the first element from the first list and combines it with each individual element from the second list, then takes the second element from the first list and combines with all elements from the second list and so on recursively. Constructing a list. A non-empty list has a head and a tail. So we can represent a list as [H|T].
4> hd([1]).
5> tl([1]).
6> [ 1 | [] ].
7> [ 1 | [2,3] ].
8> [H|T] = [1,2,3].
9> H.
10> T.
Let's write down the reduction steps.
perms([]) = [ [] ].
perms([1]) = [ 1 | [] ]
           = [ [1] ].
% produce a list with head as 1 and tail generated from the list obtained from 
% the permutation of the original list without the current head.
  = [ [1|T] || T <- perms([2]) ]
  = [ [1|[2]] ]
  = [ [1, 2] ]
% produce a list with head as 2 and tail generated from the list obtained from
% the permutation of the original list without the current head.
  = [ [2|T] || T <- perms([1]) ]
  = [ [2|[1]] ]
  = [ [2, 1] ]
Combining both we get,
perms([1,2]) = [ [[1|T] || T <- perms([2])],
                 [[2|T] || T <- perms([1])] ].

             = [ [[1|T] || T <- [[2]]],
                 [[2|T] || T <- [[1]]] ].

             = [ [1|[2]],
                 [2|[1]] ].

             = [ [1,2], [2,1] ].
perms([1,2,3]) = [ [[1|T] || T <- perms([2,3])],
                   [[2|T] || T <- perms([1,3])],
                   [[3|T] || T <- perms([1,2])] ].

               = [ [[1|T] || T <- [[2,3], [3,2]]],
                   [[2|T] || T <- [[1,3], [3,1]]],
                   [[3|T] || T <- [[1,2], [2,1]]] ].

               = [ [1|[2,3]], [1|[3,2]],
                   [2|[1,3]], [2|[3,1]],
                   [3|[1,2]], [3|[2,1]] ].

               = [ [1,2,3], [1,3,2],
                   [2,1,3], [2,3,1],
                   [3,1,2], [3,2,1] ].

Erlang Function Call Precedence

My goal is to lazy evaluate results. I want to get the nth element after performing some operations on a list of elements and I don't want to actually perform the computation unless it is required. I also want to show how to call the returned value which is a function immediately.

Generate a list with sequence 1 to 5.
1> lists:seq(1, 5).
An anonymous function that returns the double. This as such does nothing.
2> fun(X) -> 2*X end. 
An anonymous function which returns a function which when called returns the double.
3> fun(X) -> (fun() -> 2*X end) end.
We can also write this without brackets
4> fun(X) -> fun() -> 2*X end end.
Call the above function for each element in the list. We will use map for that. Let's assign the resultant list to a variable L.
5> L = lists:map(fun(X) -> (fun() -> 2*X end) end, lists:seq(1, 5)).
We know the function returns another function and results are not evaluated until we call the returned function.
Say, instead of doubling operation, we perform sightly heavier computations. Here we are not performing the computation. We intend to perform the operation only when the result is required.

Now let's get, say the 3rd element from the above list.
6> lists:nth(3, L).
But I want to get the computed result. So I have to call the returned function. Now this is where it get slightly tricky. We can call the returned function by assigning it to a variable and calling it or call it directly.
7> F = lists:nth(3, L).
8> F().
To call the returned function directly, we have to wrap the whole expression in parenthesis and then call.
9> (lists:nth(3, L))().
We cannot call it like lists:nth(3, L)() which will produce an error 1: syntax error before: '(. Richard Carlsson mentioned that it's due to the precedence rules in the Erlang grammar.

Here we are able to call it without parenthesis.
10> fun(X) -> 2*X end (3).
In this case, it works with parenthesis as well.
11> (fun(X) -> 2*X end)(2).

Saturday, 26 October 2013

Erlang for Maemo

Erlang for Nokia N900 is available from the maemo extras-devel repository.
apt-get install erlang
PS: Check if rootfs has enough space before the installation.
df -h /
df -h

Thursday, 10 October 2013

Forward Requests From Grails Spring Security Filter

I was trying to get a request to be send to a specific controller action in case of session expiry. I was trying to use redirect and later forward (to avoid additional requests from the client) method from grails. But I keep getting this error even though the params to the methods are all correct.
Message: No signature of method: com.rwi.springsecurity.filters.CustomSessionExpiryFilter.forward() is applicable
for argument types: (java.util.LinkedHashMap) values: [[controller:exampleApi, action:init, params:[...]]]
Then it struck, maybe by default we cannot use those grails methods in the spring security classes as they are under src/groovy and also the doc mentions that the method is to forward from one action to another. So in this case, to forward a request we can use methods from the servlet classes.

Forward a request to a controller action, where api is the controller and init is the action which includes query string as well.
request.getRequestDispatcher("/api/init").forward(request, response)
For a redirect request we can use response.sendRedirect() method with uri containing the necessary params like query strings appended manually. An example code snippet follows.
// Construct the redirect uri
String responseUri = {
    String uri = request.forwardURI
    String qs = request.getQueryString()
    return (qs?.size() > 0) ? "${uri}?${qs}" : uri

Monday, 7 October 2013

Groovy's JsonBuilder Nuances

JsonBuilder can be used to construct JSON objects, serialize as JSON string etc. A call() method is executed depending on the type of parameter used, and the results vary accordingly, which can be better demonstrated using examples.
import groovy.json.JsonBuilder

long userId = 12
def json = new JsonBuilder()
def result = json {   //args as block
    userId userId
json.toString()       // produces error
groovy.lang.MissingMethodException: No signature of method: java.lang.Integer.call() is applicable for argument types: (java.lang.Integer) values: [12] Possible solutions: wait(), any(), abs(), wait(long), wait(long, int), and(java.lang.Number)

The above example does not work even if the key is given as a string. Using a map as the argument to the call() method of the JsonBuilder class gives us the correct result. As we can see the above method uses a block, which can be used if the name of keys are different from any variable names in the scope.
long userId = 12
long abc = 123
long z = 987
def json = new JsonBuilder()
json userId: userId,   //args as map
     abc: abc,
     z: z
json.toString()        //{"userId":12,"abc",123,"z": 987}
It is better to use as a map instead of a block (closure), which gives the intended result in most of the cases.

In JavaScript it is pretty straight forward.
var a = 1
JSON.stringify({a: a})    //"{"a": 1}"
Below are examples where key contains the value in the variable.
json "${userId}": userId, z: z
json.toString()    //{"12":12,"z",987}
var a = 1, j = {}
j[a] = a
JSON.stringify(a)    //"{"1":1}"

Friday, 4 October 2013

Groovy: Get First n Elements from a List

A Groovy snippet to get first n elements from a list.
def a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
a.take(3)  // [1, 2, 3]

Thursday, 3 October 2013

Getting Started With GroovyFX

To run GroovyFX programs we need to have groovyfx.jar and jfxrt.jar added to the classpath. The JDK I am using is v1.8.0-ea. JavaFX SDK is bundled with JDK from Java 7u4 and above.

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Intro.groovy: 3: unable to resolve class groovyx.javafx.GroovyFX
 @ line 3, column 1.
   import groovyx.javafx.GroovyFX

1 error
The above error is thrown if groovyfx.jar is not found. The easiest way to fix this would be to use Grapes and annotate the source with @Grab('org.codehaus.groovyfx:groovyfx:0.3.1'), which will download and add the groovyfx-0.3.1.jar in the .groovy directory. Another way would be to download it from maven repository and add it to classpath manually (or use mvn).
To add it manually, create a environment variable with name CLASSPATH with value .;F:\javaLibs\groovyfx-0.3.1.jar; (update the path F:\javaLibs to reflect your directory preferences). In Windows the delimiter is ; where as under GNU/Linux it is :. This example uses Windows. There is a dot at the beginning so that the current working directory is also included. If the variable already exists, just append it to the end preceeding the appropriate delimiter.

Caught: java.lang.NoClassDefFoundError: javafx/application/Application
java.lang.NoClassDefFoundError: javafx/application/Application
Caused by: java.lang.ClassNotFoundException: javafx.application.Application
The above error is caused because Groovy could not find the jfxrt.jar file in the classpath. To resolve this append %JAVA_HOME%\jre\lib\jfxrt.jar; to the classpath variable.

The value of the CLASSPATH should look like
These are the two main errors that gets between running GroovyFX programs. Let us run a sample program from the groovyfx.org website.
// Hello.groovy
import groovyx.javafx.GroovyFX

GroovyFX.start {
    stage(title: "GroovyFX Hello World", visible: true) {
        scene(fill: BLACK, width: 500, height: 250) {
            hbox(padding: 60) {
                text(text: "Groovy", font: "80pt sanserif") {
                    fill linearGradient(endX: 0, stops: [PALEGREEN, SEAGREEN])
                text(text: "FX", font: "80pt sanserif") {
                    fill linearGradient(endX: 0, stops: [CYAN, DODGERBLUE])
                    effect dropShadow(color: DODGERBLUE, radius: 25, spread: 0.25)
Run it as
groovy Hello.groovy
or compile and run as
groovyc Hello.groovy
groovy Hello
will give the output as shown below.


Sunday, 1 September 2013

DOM Event Delegation

Event delegation can be used for handling DOM events efficiently. The basic principle behind event delegation is bubbling of events. An event handler can be attached to a parent node and any event that occurs within it's child element will bubble up if not already captured on its way to the parent node.
<div class="root">
// Using jQuery
$(document).ready(function () {
    $('.root').on('click', function (e) {
        // depending on e.target we can call necessary function (delegation)..
jsFiddle demo (uses jQuery).
//Using DOM APIs
var el = document.getElementsByClassName('root');
el[0].addEventListener('click', function(e) {
jsFiddle demo (uses DOM APIs).

Wednesday, 28 August 2013

Sync Files With rsync

rsync can be used for remote backups and syncing files. It is efficient in that it copies only changes in subsequent updates.
For using rsync from windows, install cwRsync. cwRsync works well with cmd than with cygwin bash or similar terminals under windows.
rsync -zvr -e 'ssh -p 2222' sourceDir user@ip:/home/user/dir
-z compress
-v verbose
-r recusive
-e remote shell, -p can be used if ssh runs on a different port.

Friday, 9 August 2013

Fun with OSAScript

osascript in OS X executes AppleScripts and other Open Scripting Architecture (OSA) language scripts. This allows AppleScripts to be executed from the terminal as well.
The below command will tell Finder to display a dialog with the given message.
osascript -e 'tell app "Finder" to display dialog "Hi! From OS X. Steve Jobs is watching you."'
Since we can do this using a terminal, with a bit of creativity we can have pranks. :D

SSH into Maemo

1. Install roosh (if you have not already).
2. Install OpenSSH (both server and client).
3. Next we have to set a password for the default user.
sudo gainroot
passwd user #user is the username of the default account
#enter your password when prompted
4. Start the ssh server
/etc/init.d/ssh restart #in case if it's already running
Access the phone remotely using ssh as user@the-ip-of-the-phone. You can find the IP address using the ifconfig command.

Monday, 8 July 2013

Running vnstat in OS X

vnstat can be used to monitor network bandwidth usage easily.
1. Install vnstat via mac ports
sudo port install vnstat
2. Assuming the default interface to be monitored is en0, open the vnstat.conf file under /opt/local/etc/vnstat.conf and update the parts
# default interface
Interface "en0"

# location of the database directory
DatabaseDir "/opt/local/var/db/vnstat"
3. Run the below command which will start monitoring en0
sudo vnstat -u -i en0
4. Now to run this as a service so that it starts up automatically at boot we can create a user daemon. In case of GNU/Linux, such scripts are present in /etc/init.d where as in OS X it's in /Library/LaunchDaemons.
sudo vim /Library/LaunchDaemons/local.vnstat.plist
Use the file content for local.vnstat.plist file as given below
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple/DTD PLIST 1.0//EN"
<plist version="1.0">
5. Change owner and group to root and wheel respectively.
sudo chown root:wheel /Library/LaunchDaemons/local.vnstat.plist
6. Use lauchctl to start the daemon
sudo launchctl load /Library/LaunchDaemons/local.vnstat.plist
To stop the daemon use unload.
sudo launchctl unload /Library/LaunchDaemons/local.vnstat.plist
Check the usage with
vnstat #lists complete usage
vnstat -d #lists daily usage
The 'estimated' data given is a prediction that vnstat calculates in realtime looking at the usage, hours etc.

To check whether the daemon is running use
sudo launchctl list | grep vnstat

Sunday, 30 June 2013

Node.js for Nokia N900

Node.js for Nokia N900 is available from the maemo extras-devel repository. The package name is nodejs. It gets installed to /opt. After installation add /opt/node/bin to the path (/etc/profile).

Sunday, 23 June 2013

ARM Port of Lua 5.2.2 for Maemo

Thanks to great programming by the Lua team, porting Lua 5.2.2 to ARM is just a matter of recompiling for the target CPU. This is my first port for Maemo running on Nokia N900 which has an OMAP 3430 ARM Cortex A8 SoC. The armel debian package can be downloaded from Maemo Garage. I have yet to explore on submitting to maemo-devel. It's compiled to run on any POSIX compliant OS running on ARM.
The install paths are as follows: lua, luac goes to /usr/local/bin/ and liblua.a goes to /usr/local/lib.

wget and Proxy

wget can channel it's connections via a proxy. It can be used along with Tor to download files.
wget "http://example.com" -e use_proxy=yes -e http_proxy=

Extract Audio from a Video File

ffmpeg can be used to extract audio from a video file. Install ffmpeg for the host OS (add it to the path if using Windows) and use the command as below.
ffmpeg -i video.mp4 -ac 2 -ar 44100 -vn audio.mp3
-i specify input file
-ac audio channels
-ar audio rate which is the sampling rate per second
-vn video none to not output video data
-ab audio bitrate for constant bitrate. -ab 320k means a bit rate of 320 kBit/sec.
Specifying a bit rate using -ab will produce audio file with constant bit rate (CBR). Leaving it out will give audio with variable bit rate (VBR). I recommend using VBR for better quality to size ratio.

Friday, 7 June 2013

Install Lua in Nokia N900

Lua v5.1 is available from the maemo extras-devel repository.
1. Activate extras-devel.
2. Open terminal and enter the following commands.
root #needs to be root
apt-get install lua5.1

Monday, 27 May 2013

Lua: Using split method from the string_ext module

Due to the minimalist nature of Lua, the standard library for string does not contain commonly used methods like split. However, the module string_ext contains them. Below is a snippet on how to use the split method. The point to consider here is the module we have to import in order for the method to work correctly. Importing only the string_ext module is not enough. We have to import list and strbuf modules as well.
print(string.split("Hello World", " ")) -- outputs {1=Hello,2=World}

Tuesday, 14 May 2013

HTTPBuilder Requests with Local SSL Certificate in Grails

HTTPBuilder APIs for Groovy which is a wrapper for Apache's HTTPClient allows to make HTTP/HTTPS requests from JVM. Making HTTP requests are pretty straight forward. However, HTTPS requests to local server running a self-signed SSL certificate involves a bit of work.

HTTPBuilder APIs are available to grails as a plugin, called rest. To install the plugin go to the grails project directory and run
grails install-plugin rest
1. Run the grails application with HTTPS.
2. Access the home page over HTTPS which will display a security warning. If you are using Firefox, choose 'View' in the 'Add Security Exception' dialog to view the SSL certificate. From the details tab, choose 'Export' and save as X.509 Certificate (PEM) with file name, say 'localhost' which will be saved as 'localhost.crt'.
3. Now we have to import the certificate to the Java keystore. From terminal (cmd), navigate to the location where the certificate is saved and type the following command:
keytool -importcert -alias "subdomain.your-website-domain.com" -file localhost.crt -keystore truststore.jks -storepass password1234
4. Copy the truststore.jks file created in step 3 to grails-app/conf folder.
5. RestConnector is a simple example which can be used for HTTP request. We will modify the class to support HTTPS requests.
import grails.converters.JSON

import groovyx.net.http.HTTPBuilder
import groovyx.net.http.ContentType
import groovyx.net.http.Method
import org.apache.http.impl.client.DefaultRedirectStrategy
import org.apache.http.impl.cookie.BasicClientCookie

import java.security.KeyStore
import org.apache.http.conn.scheme.Scheme
import org.apache.http.conn.ssl.SSLSocketFactory
import org.apache.http.HttpRequest
import org.apache.http.HttpResponse
import org.apache.http.protocol.HttpContext

import javax.servlet.http.HttpServletResponse
import javax.servlet.http.Cookie

import groovyx.net.http.Method
import groovyx.net.http.ContentType
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.HttpResponseDecorator

class RestConnector {
    private String baseUrl
    private HTTPBuilder httpBuilder
    private List<string> cookies

    RestConnector(String url) {
        this.baseUrl = url
        this.httpBuilder = initializeHttpBuilder()
        this.cookies = []

    public def request(Method method, ContentType contentType, String url, Map<String, Serializable> params) {
        debug("Send $method request to ${this.baseUrl}$url: $params")

        // import the key from the keystore
        def keyStore = KeyStore.getInstance(KeyStore.defaultType)
        getClass().getResource( "/truststore.jks").withInputStream {
            keyStore.load(it, "password1234".toCharArray())
        SSLSocketFactory sf = new SSLSocketFactory(keyStore)
        httpBuilder.client.connectionManager.schemeRegistry.register(new Scheme("https", sf, 443))

        httpBuilder.request(method, contentType) { request ->
            uri.path = url
            //uri.query = params
            headers['Cookie'] = cookies.join(';')
            requestContentType = ContentType.URLENC
            // sample params
            body = ['username': "${params.username}", 'password': "${params.password}", 'otherParams': "${params.otherExampleParams}"]
            headers.'Connection' = params['Connection']
            headers.'Cookie' = params['Cookie']
            println("::Cookie: -> " + params['Cookie'])
            headers.'Host' = params['Host']
            headers.'X-Requested-With' = params['X-Requested-With']
            headers.'Origin' = params['Origin']

    private HTTPBuilder initializeHttpBuilder() {
        def httpBuilder = new HTTPBuilder(baseUrl)

        httpBuilder.handler.success = { HttpResponseDecorator resp, reader ->
            resp.getHeaders('Set-Cookie').each {
                //[Set-Cookie: JSESSIONID=E68D4799D4D6282F0348FDB7E8B88AE9; Path=/frontoffice/; HttpOnly]
                String cookie = it.value.split(';')[0]
                debug("Adding cookie to collection: $cookie")
            if (resp.status == 302) {
                println('302 detected')
                return ['status': 'redirect', 'response': resp]
            debug("Resp: ${resp}")
            debug("Reader: ${reader}")
            return ['status': 'ok', 'result': reader]

        // Enable to follow redirect requests
        /*httpBuilder.client.setRedirectStrategy(new DefaultRedirectStrategy() {
            boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) {
                def redirected = super.isRedirected(request, response, context)
                return redirected || response.getStatusLine().getStatusCode() == 302
        return httpBuilder

    private debug(String message) {
        System.out.println(message) //for Gradle
6. Using the above class in a grails controller:
// ..imports
class ExampleController {
    def index() {
        String serverName = request.getServerName()
        String serverUrl = "https://${serverName}"
        RestConnector restConnector = new RestConnector(serverUrl)  //some https url here
        def result = restConnector.request(Method.POST, ContentType.JSON, "${serverUrl}", ['username': "${username}", 'password': "${password}", 'otherParam': "${otherParam}"])
        if (result.status == "redirect") {
            def resp = result.response
            def heads = resp.getHeaders()
            redirect(uri: 'redirect-uri-here')
        } else if (result.status == "ok") {
            render (result.result as JSON)

Sunday, 14 April 2013

Atheros: Share Internet Connection via WiFi in XP

Say that your computer (running Windows XP) is connected to internet via LAN and you wanted to the connection to other devices via WiFi.
1. Goto control panel -> Network Connections.
2. Right-click on the Local Area Connection and choose Properties.
3. In the Advanced Tab under the Internet Connection Sharing, enable "Allow other users to connect through this computer's internet connection".

The next part is to create an adhoc wifi connection. My netbook comes with an Atheros wireless network adapter. So I am using Atheros Client Utility to configure wireless connections. You may use Windows XP's default tool as well.
1. Open Atheros Client Utility.
2. Under Profile Management tab, click New.
3. Fill in the profile name and give an name for identifying the wifi connection under the SSID1.
4. In the Advanced tab, change network type to Ad-Hoc.
5. In the Security tab, choose Pre-Shared Key (Static WEP) and click Configure.
6. In the popup menu, choose ASCII Text for Key Entry and give a password in the Encryption Keys section for WEP Key 1 (one would be enough). Depending on the chosen WEP Key Size, the length of the key varies.
7. Click Ok and finish the configurations.
8. Back in the Profile Management, choose the currently created profile and click Activate.

Now you can connect to the internet via the newly created Ad-Hoc WiFi connection. To connecting to the network, you need to enter the same password given for the WEP key in step 6 above.

Tuesday, 2 April 2013

Immediately-Invoked Function Expression (IIFE) in Groovy & JavaScript

Immediately invoked function expressions are anonymous function blocks executed soon at the end of the block giving the return value. IIFEs are very common in JavaScript.
// IIFE in js
(function(arg) {
    if (arg === 1)
        return "one";
        return "not one";
In Groovy the same thing can be done using anonymous blocks which the language names as 'closure'. It is not the lexical closure that we are talking about, though it can be. The 'Closure' in Groovy is just a block of code.
Anyway we can have an IIFE in groovy using blocks and invoking it at the end of the block as shown below. Since the evaluated value is returned, we can omit the return statement.
// IIFE in Groovy
{arg ->
    if (arg == 1)
        "not one"

Thursday, 7 March 2013

Bookmarks Organizer Google Chrome Extension

Bookmarks Organizer Google Chrome Extension helps us in keeping the bookmarks sorted. By default Chrome does not sort bookmarks by title. This extension monitors for newly added or moved bookmarks and auto arranges them in ascending order by title. There is a reorder button to manually order the whole bookmark, which can be used initially after installation. The only down side is that there is API restriction on the number of bookmarks that can be reordered (moved) per min, per hour and the number is a bit low.
This extension is available at Chrome Web Store. The code is licensed under GNU GPL v3 and is available at the github repository.

Monday, 4 March 2013

Copy Files with Excludes

The cp command does not have an excludes option. One way to copy files ignores some files or directories is to create a tarball. The tar command has an exclude option. The exclude patterns can be mentioned in a separate file and passed in to the tar command.
# Directory Structure
│   .git
│   .gitignore
│   books.html
│   book.js
│   build.sh
│   buildExcludes
│   main.js
│   manifest.json
│   └───BO
│       │   books.html
│       │   books.js
│       │   main.js
│       │   manifest.json
│       │
│       └───res
│           └───icons
│                   bo-128.png
│                   bo-16.png
│                   bo-256.png
│                   bo-32.png
│                   bo-48.png
│                   bo-512.png
│                   bo-64.png
In the above directory structure, I want to copy certain file to bin/BO but ignore others like .git, fla files in the res/icons directory, the build scripts etc. For that first create an file say buildExcludes with the exclude pattern.
Content of the exclude file is given below.
Create the tar, deflate to the destination directory and delete the tar once done.
tar -cvf bo.tar * -X buildExcludes  #create tar
tar -xvf bo.tar -C bin/BO/          #deflate to destination directory
rm -f bo.tar                        #cleanup

Wednesday, 20 February 2013

Get Timestamp for the Present Day in Java

// Snippet for getting timestamp in milliseconds for the present day with time taken as 00:00:00
// Eg: ts for '2013-02-19'
public long getTsForToday() {
    Calendar cal = Calendar.getInstance();
    int year = cal.get(cal.YEAR);
    int month = cal.get(cal.MONTH);
    int date = cal.get(cal.DATE);
    cal.set(Calendar.YEAR, year);
    cal.set(Calendar.MONTH, month);
    cal.set(Calendar.DATE, date);
    return cal.getTimeInMillis();

Tuesday, 19 February 2013

Access Service Class From src/groovy Classes

The groovy classes placed in the src/groovy folder does not have dependency injection by default. However we can can access service classes using servlet context.
package com.example.ExampleClass

import org.codehaus.groovy.grails.web.context.ServletContextHolder
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes

class ExampleClass {
    def context = ServletContextHolder.servletContext.getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT)
    def exampleService = context.exampleService