Archive for the ‘Web’ Category.

JBoss JMX extensions to EJB3

I don’t particularly like developing on JBoss - I think its bloated and slow. But with EJB3 the platform has become more viable. The turn around time to get a relatively complex application with web services etc. done is great.

One thing I like about JBoss 5.x are the JMX extensions to EJB3. Its really amazing how simple installing a JMX MBean is. Let’s say I have to write  a CalculatorService represented by this interface:

package net.ahlawat.cricket;

import javax.ejb.Remote;

import org.jboss.ejb3.annotation.Management;

@Management
@Remote
public interface CalculatorService {
	public double add(double a, double b);
	public double subtract(double a, double b);
	public double performOperation(double a, double b);
	public String getDefaultOperation();
	public void setDefaultOperation(String operation);
}

The interesting annotations here are @Management which tells JBoss deployer that the interface is to be bound as a JMX MBean. The implementation of this bean can be simple pojo - listed here.

package net.ahlawat.cricket;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.ejb3.annotation.Service;

@Service(objectName = "ahlawat:service=CalculatorService")
public class CalculatorServiceImpl implements CalculatorService {
	static Log logger = LogFactory.getLog(CalculatorServiceImpl.class);

	Method defaultOperation;

	@Override
	public double add(double a, double b) {
		return a+b;
	}

	@Override
	public String getDefaultOperation() {
		return defaultOperation.getName();
	}

	@Override
	public double performOperation(double a, double b) {
		try {
			BigDecimal bd = (BigDecimal) defaultOperation.invoke(new BigDecimal(a), new BigDecimal(b));
			return bd.doubleValue();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}

		return Double.NaN;
	}

	@Override
	public void setDefaultOperation(String operation) {
		try {
			Method m = BigDecimal.class.getMethod(operation, BigDecimal.class);
			logger.info("Setting default operation to " + operation);
			defaultOperation = m;
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}

	}

	@Override
	public double subtract(double a, double b) {
		return a-b;
	}

	//lifecycle methods
	public void create() throws Exception {
		logger.info("Creating service");
	}

	public void start() throws Exception {
		logger.info("Starting service");
		setDefaultOperation("add");
	}
}

The only interesting thing here is @Service - which tells Jboss that this is a singleton bean. And the fact that MBean lifecycle methods like create() and start() are available to be implemented here.

The complete list of life cycle methods are:

   void create() throws Exception;
   void start() throws Exception;
   void stop();
   void destroy();

Once this is jar’d up and deployed to Jboss - you can go to jmx-console and see that the service is visible:

jmx-console

jmx-console

You can also look up the bean using the default JNDI name CalculatorServiceImpl/remote

public class Main {
	public static void main(String[] args) throws Exception {
		InitialContext ctx = new InitialContext();

		CalculatorService cs = (CalculatorService)ctx.lookup("CalculatorServiceImpl/remote");

		System.out.println(cs.add(2.1, 3.2));
	}
}

Here is the jndi.properties:

#jboss JNDI properties
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.provider.url=jnp://localhost:1099
java.naming.factory.url.pkgs=org.jnp.interfaces

And you can also inject the referece to another EJB using the @EJB annotation like this:

@Stateless
public class PlayerServiceImpl implements PlayerService {
	static Log logger = LogFactory.getLog(PlayerServiceImpl.class);

	@PersistenceContext(unitName = "default")
	EntityManager entityManager;

	@EJB
	CalculatorService calculatorService;

	@PostConstruct
	public void gotCalculator() {
		System.out.println(">>>>>>>>>>>>>>>>>> " + calculatorService.add(1.0, 1.0));
	}

...
}

Really small amount of code and guess what - no XML. I really like it.

FTP made easy with Python

I am falling in love with python every day - its amazing how simple it makes tasks. The indented syntax and the functional aspects of the languages are growing on me every day.

Python comes with a bunch of libraries to make your life easy and one of them is ftplib. Here is a little script to list, chage directories and ultimately download a binary and a text file:

from ftplib import FTP
import getpass
serverName = "ahlawat.net"
ftp = FTP(serverName, raw_input("Username: "), getpass.getpass())
#change working directory
ftp.cwd("ftp")

#list the files
print ftp.dir()

baseDir = "c:/dev/python/pytest/pkg/"

#transfer a text file - some script
f = open(baseDir + "testUrl.groovy", "w")
ftp.retrlines("RETR testUrl.groovy", lambda x : f.write(x))
f.close()

#trasnfer a binary file - a png image
f = open(baseDir + "cube_logo.png", "wb")
ftp.retrbinary("RETR cube_logo.png", lambda x : f.write(x))
f.close()

More to come ..

Opensource web collaboration and conferencing in java and flash

I found it hard to believe that no one in the open soruce world found time to write an alternative to the popular webex (now owned by Cisco) and gotomypc services. I need these services daily to demo code and also to give tutorials to friends and family so I started to search.
And it didn’t take me long – I discovered dimdim. The service looks really promising and its free conferencing for upto 20 users, which more than meets my needs.


Here is the really interesting bit – there is a open source (GPL) community edition of this product. What I love about dimdim is that it’s written in java and uses the tomcat/mysql/terracotta stack and I intend to tweak it and get it running on my linux box minus terracotta and litghtHTTPD very soon. Let’s see how it goes. It’s in beta and the product is very functional.


Cant wait I haven’t been this excited in a long time.

Consuming Seeqpod REST web service to search media

I was recently introduced to seeqpod it’s quite a nifty search engine - searches music and other media on the internet.

The basic interface of seeqpod is in flash - so when you finish searching some music you will see that the player will play the searched URL in the flash player within the same UI. The awesome thing is that the website exposes a REST service that can be utilized to search media and get the URLs. All you have to do is register for it.

To play around with it I registered and I love it - you can search and listen to music or a TV show in your favourite media application.

Here is a little groovy code that consumes the service, dumps the results in a HTML file and opens the file in your browser so you can click and download/listen. A lot of stuff in very little code.
import groovy.util.*;import groovy.xml.*;

println "please enter your mp3 query: ";def query = (new BufferedReader(new InputStreamReader(System.in))).readLine();def formattedQuery = query.replaceAll(" ", '+')println "Searching for ${query}"

def queryResponse = new URL("http://www.seeqpod.com/api/v0.2/api_name/music/search/${formattedQuery}/1/100/").text;

def xml = new XmlSlurper().parseText(queryResponse);

//iterate and output the values

def tracks = xml.trackList[0].track

def html = new MarkupBuilder(new FileWriter(”seeqpod.html”))

html { body(style:”font-family:verdana;”) { h2 “Search results for ${query}” for (track in tracks) { ul { li { div { a(href:track.location, “${track.title} by ${track.creator}”) } // end div } // end li } // end ul } // end for } // end body} // end html

new AntBuilder().exec(executable:”explorer”) { arg(value:”seeqpod.html”)}
works quite well - so running this:
C:\Users\pranay\Desktop>groovy seeqpodserach.groovyplease enter your mp3 query:ozzy osbourneSearching for ozzy osbourne [exec] Result: 1

C:\Users\pranay\Desktop>
produces a nice page like this with google like speed!!

Google chart API - Using charts in web applications has never been this easy

I have been playing around with google charts api for now and I think they are simply great. Send in parameters in a URL and get back a spanking chart:

So a URL like:
this

will give a nice chart like this:

Not sold yet? I will say a few things that will hopefully impress you. The image that you see here is size optimized (9.6K), the colors are extrapolated from a single chco parameter that is passed in the URL and the generation is lightning quick (imagine taking this processing away from your own hardware a few thousand times a day) and its free!!

Mention something like this and people always say, how about chart customization, can I control the colors etc. and here is the scoop - you can customize the living air out of this chart, colors, markers, grids, axes, labels, title, size, legends and so on and so forth. I am very practical when using free libraries, I always look at the ease of use and productivity first.
I always tell this to people - if you can get 90% of what you want with 20% of the effort - its a good deal. Work around the remaining 10%, you will still be better off.

One think I disliked about google charts is the data encoding. I think its stupid that you cannot pass in negative data and you have to play around with labels and colors to achieve this concept. At school I did a lot of matlab and I loved how intuitive it was to simply pass in an array of numbers and the software churned out the correct chart 95% of the time.

Obviously when passing parameters in a URL is a limiting way - but I don’t understand why color extrapolation can be done but not data normalization.

One really cool thing about google charts is that is seamlessly integrates into grails. To start using google charts, install the google chart API


C:\dev\europa\workspace\app>grails install-plugin google-chart

Welcome to Grails 1.0.3 - http://grails.org/
Licensed under Apache Standard License 2.0
Grails home is set to: C:\groovy\grails-1.0.3

Base Directory: C:\dev\europa\workspace\app
Running script C:\groovy\grails-1.0.3\scripts\InstallPlugin.groovy
Environment set to development
[mkdir] Created dir: C:\Users\pranay\.grails\1.0.3\plugins\google-chart
[get] Getting: http://plugins.grails.org/grails-google-chart/tags/RELEASE_
0_4_6/grails-google-chart-0.4.6.zip
[get] To: C:\Users\pranay\.grails\1.0.3\plugins\google-chart\grails-google
-chart-0.4.6.zip
….
[copy] Copying 1 file to C:\dev\europa\workspace\app\plugins
[mkdir] Created dir: C:\dev\europa\workspace\app\plugins\google-chart-0.4.6
[unzip] Expanding: C:\dev\europa\workspace\app\plugins\grails-google-chart-0
.4.6.zip into C:\dev\europa\workspace\app\plugins\google-chart-0.4.6
Compiling plugin google-chart-0.4.6 … …
[groovyc] Compiling 3 source files to C:\Users\pranay\.grails\1.0.3\projects\a
pp\classes
[mkdir] Created dir: C:\dev\europa\workspace\app\web-app\plugins\google-char
t-0.4.6
[copy] Copying 1 file to C:\dev\europa\workspace\app\web-app\plugins\google
-chart-0.4.6
Loading with installed plug-ins: ["googleChart", "acegi"] …
Executing google-chart-0.4.6 plugin post-install script …
Plugin google-chart-0.4.6 installed
C:\dev\europa\workspace\app>groovy console
Caught: java.io.FileNotFoundException: C:\dev\europa\workspace\app\console (C:\d
ev\europa\workspace\app\console)

C:\dev\europa\workspace\app>grails console

Just this simple command will give you a slew of tags like g:lineChart, g:barChar, g:pieChart etc.

The get parameters to the google API URL can be exposed as parameters to the tags.

So the following code inside a GSP generates a sine curve (note that I have to normalize the data (doubles between 0.0 and 100.0) so that its compatible with google charts - but I can label the data to get a perception of correct charts. Also this specific chart takes care of negative numbers as well.


<!– drawing a sine curve using the g:line –>
<%
def line = (1..50).toList()
def values = line.collect {Math.sin(it/10)}
def max = values.max()
def min = values.min()

//normalize
def normalized = values.collect {((it-min)/max) *100}

%>

<g:lineChart title=’Sample Line Chart’
type=’lc’
dataType=’text’
axes=”x,y”
axesLabels=”${[0:[1,25,50], 1:[-1,0,1]]}”
gridLines=”20,50,1,0″
colors=”['ccccff']“
data=’${normalized}’ />

Doing so generates a sine curve like this:

I would encourage you to chart yourselves out - because its never been this easy!

High scalability websites using webwork / struts 2 - my first thoughts on the framework


I was recently reading up on struts 2. Its a very nimble framework. Its architecturally very elegant. The crux of the framework is implemented as interceptors. A number of interceptors each responsible for individual units of work carry out much of the activity. So the actual transfer of data from the request to the model, validation, conversion etc. are all individual interceptors.

The cool thing about the framework is that individual interceptors can be grouped into “interceptor-stacks” and applied to specific requests. Very cool idea. I think one of the strengths of JSF is the well defined life cycle and corresponding event and phase listeners. But while JSF expects you to do a fair job working and treating this life cycle as a black box. Struts 2 expects you to rip the gut of the framework open and implement your own interceptors adding them in the stack.

The idea of interceptors and encapsulation of cross cutting concerns is nothing new – but the ease and elegance with which struts 2 applies this to web applications is very refreshing.

Internally you can expose views to the model using JSPs, velocity or freemaker (all using custom tags/macros). The framework integrates well with sitemesh for templating. The tags and macros and the framework use OGNL (object graph navigational language) to ferry data to the views and applying data to the models (during request processing). OGNL exposes a very strong syntax to apply values to the pages (and apply values back). To be very honest in the basic applications that I played with I found it very similar to EL.

Unfortunately this is where the framework falls to the face – I started to write a basic web application using struts 2. The basic hello world page was taking some time to load (30-100 ms). I investigated a little bit and found out that OGNL was to blame. I google’d the topic and found out that other people are facing similar issues.

http://www.mail-archive.com/dev@struts.apache.org/msg26464.html

There is also a frusterated bug about this:

https://issues.apache.org/struts/browse/WW-2036

There are other performance issues with struts as well. I am personally very comfortable and productive using the JSF – myfaces + facelets + prototype stack. I began to investigate Struts 2 for a high volume website that I would have potentially worked on. Unfortunately it’s like I thought. People are still having a better experience with Struts 1. I personally feel using Spring MVC + webflow over spring and hibernate back end will prove to be a better option given the performance issues.

I am a little disappointed I love the framework and would love to see the authors do something about the core performance. Putting up a tweaking page on the wiki is simply not good enough. Also I think the authors and engineers can do better with the documentation. Its very fragmented and all over the place. I am not done with struts yet – I will put in on the back burner and continue.