JSF & Richfaces - Display Math On Web

Last week, I attended an event, organized by 'Nuremberg/Nurnberg(Germany) Herbstcampus', in which, bigtime folks from the software industry (specially from the Java world) like James Gosling (Founder of Java), some core developers from the Hibernate and JSF were present.

Later, I worked on a sample JSF-Facelets-Richfaces application. Instead of creating a boring sample application, I thought of working on some interesting stuff. This application, I created deals with "How To Display Math On The Web?" and uses a 'jsmath' package, which is a open source javascript library. This library has 2 options for users to display math on web: Using 'TeX Fonts' (which can be installed on your system) or Images (which are in jsmath package). I used the first option, just to make it easier. If you want, you can download these fonts from the JSMath site.

Below is the sample facelets file of this application, which displays 'Math' expressions or equations dynamically, as you type the 'Tex Expression' as input:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"


<STYLE TYPE="text/css">
.math {visibility: hidden}
<SCRIPT>jsMath = {Controls: {cookie: {scale: 133}}}</SCRIPT>
<SCRIPT src="jsMath/jsMath.js"></SCRIPT>

function process() {        

<h:outputText value="Enter Some Math Expression: " />
<h:inputTextarea id="intext" value="#{mathBean.text}" style="width:400;height:100">
<a4j:support event="onkeyup" reRender="outPanel" oncomplete="process()"/>

<a4j:outputPanel id="outPanel">
<DIV CLASS="math">        
<h:outputText id="outtext" value="#{mathBean.text}"/>                        

As you see (in the above code), I have a input text area, where you type your 'Tex Expression', which is rendered dynamically and displayed in the "Math" div, which should be surrounded by "a4j:outputPanel" tags, to be rendered on AJAX response. The input text area, has "a4j:support" tags, which creates a AJAX request, based on the "onkeyup" javascript event and rerenders the outputPanel, which contains the 'Math' div. There is also a "oncomplete" attribute for this tag, which calls a javascript function of jsMath package, on complete of the AJAX cycle and renders the TeX expression that you typed, into a Math expression/equation.

Below is a demo, which shows how it works:

And below is the code for 'MathBean':

package com.math;

public class MathBean {
private String text;

public void setText(String text) {
this.text = text;

public String getText() {
return text;

Java 6 - ArrayDeque

Java programmers are getting rich day by day (as the new versions and other frameworks come into existence), as the Java Collections Framework is hosting a lot of different datastructures and algorithm implementations. The latest one I came across is 'ArrayDeque' from Java version 6.

ArrayDeque is an implementation of the 'Deque' interface, which is a short form for "Double Ended Queue's". Double Ended Queue's extend 'Queue' and support adding and removing elements from both ends. In a Queue, you can add from one end and remove from the other. Also, Deque's can be used as a Queue and also a 'Stack'. ArrayDeque has no capacity restrictions like some other data structures (although you can specify that in one of its constructors). ArrayDeque is not threadsafe, as other collections like HashMap, et al. If you want it thread-safe, use 'LinkedBlockingQueue', which implements the 'BlockingQueue' interface, which further extends from 'Deque' interface.

A 'Deque' can be traversed from both directions programmatically using 'iterator' and 'descendingIterator' methods. Deque is doubly linked and can be compared to 'LinkedList', which also implements a 'Deque', apart from List. In LinkedList, you can access an element randomly, by the element's index, which you cant do in Deque's. It was designed this way to make it more efficient.

This kind of datastructure, which can be operated as a 'Queue', 'Stack' and can be traversed from both ends, is pretty useful in certain scenarios. A couple of 'backtracking' and other useful algorithms can be easily implemented with this kind of 'off-the-shelf' datastructures available from the 'Java Collection Framweork'.

A couple of months/years back, I had to code my own implementation to implement some algorithms. Ofcourse, its fun and a learning experience, but with ready-made stuff like this, it saves some time for a Java developer. And ofcourse, its better and useful for any developer to know the implementation 'behind-the-scenes'. By the way, Java is getting more abstract day by day (more high-level) with all these implementations and frameworks popping up from everywhere.

Below is a trivial Java program, for testing/demonstrating the new 'ArrayDeque' class from 'Java 6 Collections Framework':

import java.util.ArrayDeque;
import java.util.Iterator;

public class ArrayDequeTest
public static void main(String[] args) 
ArrayDeque arrDeque = new ArrayDeque();


for(Iterator iter = arrDeque.iterator();iter.hasNext();) {



for(Iterator iter = arrDeque.iterator();iter.hasNext();) {


for(Iterator descendingIter = arrDeque.descendingIterator();descendingIter.hasNext();) {

System.out.println("First Element : " + arrDeque.getFirst());
System.out.println("Last Element : " + arrDeque.getLast());
System.out.println("Contains \"porsche\" : " + arrDeque.contains("porsche"));



for(Iterator iter = arrDeque.iterator();iter.hasNext();) {



for(Iterator iter = arrDeque.iterator();iter.hasNext();) {


for(Iterator iter = arrDeque.iterator();iter.hasNext();) {

System.out.println("Popped Element : " + arrDeque.pop());


for(Iterator iter = arrDeque.iterator();iter.hasNext();) {

System.out.println("\n Size of Array Deck : " + arrDeque.size());

System.out.println("\n Peek : " + arrDeque.peek());

System.out.println("\n Peek First : " + arrDeque.peekFirst());
System.out.println("\n Peek Last : " + arrDeque.peekLast());


for(Iterator iter = arrDeque.iterator();iter.hasNext();) {

System.out.println("\n Poll First : " + arrDeque.pollFirst());
System.out.println("\n Poll Last : " + arrDeque.pollLast());


for(Iterator iter = arrDeque.iterator();iter.hasNext();) {

System.out.println("\n Poll : " + arrDeque.poll());

System.out.println("\n Peek First : " + arrDeque.peekFirst());
System.out.println("\n Peek Last : " + arrDeque.peekLast());

arrDeque.offerLast("what the heck?");


for(Iterator iter = arrDeque.iterator();iter.hasNext();) {

System.out.println("\n Get First : " + arrDeque.getFirst());
System.out.println("\n Get Last : " + arrDeque.getLast());

System.out.println("\n Element : " + arrDeque.element());

Object[] objArray = arrDeque.toArray();
System.out.println("\n Object Array Size : " + objArray.length);

String[] strArray = (String[]) arrDeque.toArray(new String[0]);
System.out.println("\n String Array Size : " + strArray.length);

ArrayDeque arrDequeClone = arrDeque.clone();
System.out.println("Clone Size : " + arrDequeClone.size());

System.out.println("arrDeque == arrDequeClone : " + (arrDeque == arrDequeClone));

System.out.println("arrDeque.equals(arrDequeClone) : " + arrDeque.equals(arrDequeClone));

For more info, check the docs from Sun's website. I'll post some more info, if I happen to spend some more time and implement an algorithm or any other imp stuff, using this datastructure.

Dont Smack The Stack (Deal With Stack Overflow Exceptions)

At times, Java programmers come across this scenario when they have to handle 'Stack Overflow' exception in Java. This probably and mostly happens due to some petty mistakes in the code. Stack overflow happens when all the memory that is allocated to the stack is totally used. Most of the programming languages have limited memory for the stack. So, when stack memory is totally used, it results in program crash.

Stack overflow usually happens when a recursive function is used infinitely (which is probably due to some naive coding mistake). Alternatively, it can also happen when a very large stack variable is used.

Some programming languages (specially functional programming languages like 'Scheme') use 'Tail Recursion' to avoid 'Stack Overflow' errors and to improve efficiency. In this kind of technique, the last statement/operation in a method/function is a recursive call. By this use of logic, recursions can easily be transformed to iterations and thus help in effective use of memory/data-structures.

Below are some scenario's in which this kind of java exception happens:

1) Infinite Recursion:

If you have designed java applications with interfaces or abstract classes, sometimes you might bump into situations, where in, you have overridden a method from some interface/class that you are implementing and you mistakenly called the method of the interface/class, instead of calling some other method or implementing a totally new functionality. This code would not throw any compile time errors. But, at runtime, you would be surprised to see 'Stack Overflow' exceptions. Below is one trivial example:

public interface Interface1 {
public void doSomeShit();

Here's a class that implements 'Interface1', overrides the method and calls the same method. This is pretty stupid coding, but there might be scenario's where you might not notice because of code complexity or due to neglect.

public class Interface1Impl implements Interface1
public static void main(String[] args) {
Interface1Impl i = new Interface1Impl();


public void doSomeShit() {

The above program compiles fine, but throws 'Stack Overflow' exception, at runtime.

Example 2:

public class StackOverflowDemo1
public static void main(String[] args) 
StackOverflowDemo1 sofd = new StackOverflowDemo1();

public void method1() {

public void method2() {

Example 3:

public class StackOverflowDemo2
public static void main(String[] args) 
StackOverflowDemo2 sofd = new StackOverflowDemo2();

public String valueOf(Object obj) {
return valueOf(obj);    

The above code throws 'Stack Overflow' exception, as you are doing nothing special, but overriding the 'String' objects 'valueOf' method and calling it again.

The JVM (Java Virtual Machine) uses stack to store the state of java method invocations (excluding Native methods). The state of a method is in its local variables, parameters, return value and whatever business/plain logic involved in that method. Java's programming model further splits 'Java Stack' into 'Stack frames' (which is probably a programming concept for efficiently handling the state of a method, et al things). Each and every method's state is associated with a particular stack frame. When the method completes, the stack frame is deallocated. This is how the methods parameters, local variables, return type variables are always thread safe.

If you have problems with Java stack or if you want to increase the size of Java Stack, you can use the following command:

Java - Xss Stack-Size

Replace the 'Stack-Size', with the size of memory that you need.

Thats it! Happy coding and 'Protect The Stack'! ;-) (Now, the heap's calling..huh)

Spiral Walking

Problem: Spiral Walking

Description: The problem is to traverse a rectangular grid of cells, starting from the top first cell on the left. Initially, you start in the "right" direction and move through the grid, cell by cell. Each and every cell must be visited only once. If you end up in a cell, which is the last in that direction (or already visited), change direction and move forward. This should be done til you cover all the cells in that rectangular grid.

Example: (for a 4*3 grid)

- - >
^ > |
| v |
< - v

Java Solution: In this solution, I'm using direction flags and a boolean matrix (to identify if a cell has been already visited or not) and returning a string[][] array of the resulting spiral path. I've not optimised the code for clarity and other reasons. Please feel free to comment/suggest with any other ideas or positive criticism. The Java implementation is as below:

Since each and every cell has to be visited, this algo might be slow for large input values. But for this Java implementation, I've used 'int' for 'row' and 'col'. So, you cant specify large input values anyways, although it still matters.

The code above outputs the following string[][] array, when provided with an input of 10 rows and 10 columns:

- - - - - - - - - >
^ - - - - - - - > |
| ^ - - - - - > | |
| | ^ - - - > | | |
| | | ^ - > | | | |
| | | | < v | | | |
| | | < - - v | | |
| | < - - - - v | |
| < - - - - - - v |
< - - - - - - - - v

nth Fibonacci Number

If someone asks you how to find the nth number in the Fibonacci sequence, remember the below formula:

This formula is called 'Binets Formula' and is based on the 'Golden Ratio'.

Other References:

1) Wolfram Mathworld

2) Let Me Google For You


Groovy - Basics

Yesterday, I was reading a bit about scripting languages and started playing with ‘Groovy’, which is an alternative to ‘Java’. You can say that it’s a bit higher-level language than Java, as it is built on Java libraries (or classes) and provides one more abstraction layer. Groovy, which is a ‘Dynamic Language’ (dynamically typed) was built to provide a scripting language for the Java platform, along the lines of Python, Ruby and Perl. Below are some imp points:

1) The Groovy compiler can be used to generate ‘Java Bytecode’, which can be integrated with any other java module/project.

2) Most of the Java code is also a valid syntax for Groovy.

3) Groovy is dynamically typed, whereas Java is static and strongly typed. Dynamically typed languages have lesser code, but more execution time.

4) Groovy also provides special XML processing through the classes XmlParser, XmlSlurper, DOMCategory.

Apart from these, Groovy has features like ‘Dynamic Typing’, ‘Closures’ and ‘builders’. Also, it’s pretty useful for testing as it supports unit-testing and mocking out-of-the-box.
After doing a bit of reading and coding some basic scripts, I tried to code a Groovy solution for the Java code that I wrote for solving the “Google’s Billboard Puzzle” (from my other blog). It’s for calculating “Euler’s Number (e)” , which is pretty basic and simple code. Here’s the code:

BigDecimal e = new BigDecimal(1.0G)
BigDecimal temp = new BigDecimal(1.0G)

for(i in 1..100) {
temp *= i
e += new BigDecimal(”1″).divide(temp, new java.math.MathContext(10000))

println(”e : ” + e)
println(”length of e calculated : ” + (e+”").length())

As you can see, the ‘Groovy’ script also has ‘Java’ code in it (and is valid). Since, Groovy is a dynamically typed language, it took more time than the Java code took, to produce the solution.

Here’s one more script, which outputs the ‘hashcode’ of a string:

def str = “abc”
int hashcode = 1;
int len = str.length()

for(i in 0..(len-1)) {
hashcode = 31*hashcode + str.charAt(i)

println(”hashcode : ” + hashcode)

The above code is a naive approach to calculate the ‘hashcode’ and is not a cryptographically secure function. Its based on the formula “s[0] * 31n − 1 + s[1] * 31n − 2 + … + s[n − 1]“, which is actually ‘Rabin-Karp Algorithm (RK)’. One might be wondering why there in ‘31′ in that Math expression. Its because Java’s int is ‘32′ bit, in length.

Groovy can also be used to test web applications, webservices, et al. Groovy can be used to test webservices in the following way:

* Act as a normal webservice client
* Use ‘WebTest’
* Use ‘SoapUI’

Ok..I decided to code a webservice client and googled for ‘Free Publicly Available Webservices’ and found a couple of websites with publicly available webservices. I picked the CDYNE’’s ‘Profanity Filter’ webservice (which filters words that are considered profanity) and provided the WSDL url to the Groovy script. Here’s the script (minimalistic):

import groovyx.net.ws.WSClient

def proxy = new WSClient(”http://ws.cdyne.com/ProfanityWS/Profanity.asmx?wsdl”, this.class.classLoader)

def result = proxy.SimpleProfanityFilter(”You crappy bugga!”)

For the above script to run on ‘Groovy Console’, you have to copy the ‘groovyws’ jar file into Groovy’s ‘lib’ directory.