Posts tagged ‘development’

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.

Debugging oracle constraints

On more than one occasion I have been stumped with a message like this.

java.sql.BatchUpdateException: ORA-00001: unique constraint (SYSTEM.SYS_C0089989) violated

Apart from blaming oracle for being lazy and not putting the table/column name in the error message - there is nothing else that comes to mind when I see something like this.

Finding out the table and the constraint - you can connect to plsql and execute this query:

select constraint_name, constraint_type, table_name from user_constraints where constraint_name like 'SYS_C0089989';

The result is something like this:

"CONSTRAINT_NAME","CONSTRAINT_TYPE","TABLE_NAME"
"SYS_C0089989","P","JOBAUDIT"

This information gives you the table name and the constraint type on that table.

Here is what the constraint type columns mean:

C   Check on a table                Column
O   Read Only on a view           Object
P   Primary Key                       Object
R   Referential AKA Foreign Key  Column
U   Unique Key                        Column
V   Check Option on a view       Object

So looking back I know my code is trying to insert a duplicate id in the table.

Implementing a pagination filter in Hibernate and Spring

Database based pagination is a common requirement in database driven applications. With application frameworks like spring and hibernate and newer language features like generics development of pagination features is seamless.

Lets take a look at this example -

First lets define a data access object (DAO) - an interface used by the application to perform CRUD operations and (in our case) pagination:

public interface Dao {
    public T get(Serializable id);
    public Collection getByExample(T entity);
    public Collection getByExample(T entity, PaginationFilter filter);
    public long countByExample(T entity);
    public void delete(T entity);
    public void persist(T entity);
    public void saveOrUpdate(T entity);
}

The method to note here is

getByExample(T entity, PaginationFilter filter);

The pagination filter is an object that encapsulates:

  1. The start row
  2. The max number of rows
  3. The sorting criteria

Here is the listing of the pagination filter:

public class PaginationFilter {
    public enum Order {
        ASCENDING,
        DESCENDING
    }

    public class SortingCriteria {
        private String column;
        private Order order;

        public SortingCriteria(String column, Order order) {
            this.column = column;
            this.order = order;
        }

        public String getColumn() {
            return column;
        }

        public Order getOrder() {
            return order;
        }
    }

    private int firstResult;
    private int maxResult;
    private List sortingCriterias;

    public PaginationFilter(int firstResult, int maxResult) {
        this.firstResult = firstResult;
        this.maxResult = maxResult;

        this.sortingCriterias = new ArrayList();
    }

    public PaginationFilter addSortingCriteria(String field, Order order) {
        this.sortingCriterias.add(new SortingCriteria(field, order));
        return this;
    }

    public int getFirstResult() {
        return firstResult;
    }

    public int getMaxResult() {
        return maxResult;
    }

    public List getSortingCriterias() {
        return sortingCriterias;
    }
}

Lets now take a look at the implementation of the DAO - the rest of the methods are not very interesting so lets limit the discussion to the methods with PaginationFilter:

    public Collection getByExample(final T entity, final PaginationFilter filter) {
        if (filter == null)
            return getByExample(entity);
        return (Collection) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Criteria criteria = createCriteria(entity, filter, session);
                return criteria.list();
            }
        });
    }

    public long countByExample(final T entity) {
        return (Long) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Criteria criteria = createCriteria(entity, null, session);
                criteria.setProjection(Projections.rowCount());
                Object object = criteria.uniqueResult();
                return new Long(object.toString());
            }
        });
    }

    private Criteria createCriteria(T entity, PaginationFilter filter, Session session) {
        Criteria criteria = session.createCriteria(entity.getClass());
        criteria.add(Example.create(entity));

        if (filter != null) {
            criteria.setMaxResults(filter.getMaxResult()).setFirstResult(filter.getFirstResult());

            for (PaginationFilter.SortingCriteria sortingCriteria : filter.getSortingCriterias()) {
                criteria.addOrder(
                        sortingCriteria.getOrder() == PaginationFilter.Order.ASCENDING?
                                Order.asc(sortingCriteria.getColumn()) :
                                Order.desc(sortingCriteria.getColumn()));
            }
        }

        return criteria;
    }

That is all the code you need to implement pagination with Hibernate:

So to test this code out - let us consider a test entity:

@Entity
public class TestEntity implements Savable{
    @Id
    @GeneratedValue
    private Long id;
    private String name;
    private String address;
.... //Getters and setters
}

Here is a little test that exercises the PaginationCode with the TestEntity:

    @Test
    public void testSorting() {
        PaginationFilter filter = new PaginationFilter(0,26);
        filter.addSortingCriteria("name", PaginationFilter.Order.DESCENDING);
        TestEntity testEntity = new TestEntity();
        List list = (List) genericDao.getByExample(testEntity, filter);
        assertEquals(26, list.size());
        assertEquals("a", ((TestEntity) list.get(25)).getAddress());
        assertEquals("z", ((TestEntity) list.get(0 )).getAddress());
    }

That is it. Imagine having to write filtering/pagination code for a straight up JDBC. Not so much fun. It also amazes me how nice and clean Java generics can make your code. This sceheme works very nicely for me.

High speed database neutral batch inserts/updates using Spring and Hibernate

I have been working on hibernate for a while now and recently wanted to get some data in really fast (basically using SQL batching). 

Here is the entity:

@Entity(name = "Person")
public class PersonEntity {
    @Id
    int id;
    String fName;
    String lName;
    int age;

    public String getFName() {
        return fName;
    }

    public void setFName(String fName) {
        this.fName = fName;
    }

    public String getLName() {
        return lName;
    }

    public void setLName(String lName) {
        this.lName = lName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

1. Modify the *context.xml file to include the following hibernate jdbc parameter:

<prop key="hibernate.jdbc.batch_size">20</prop>

2. Write the code with session clearing every BATCH_SIZE. For convinience sake I am extending the HibernateDaoSupport class but you can use the sessionFactory directly. Here is what I have:

@Transactional
public class HibernateInsertTest extends HibernateDaoSupport implements HibernateInsertInterface {
    private final int BATCH_SIZE = 20;
    private final int NUMBER_OF_ENTITIES = 100000;
    @Transactional(propagation = Propagation.REQUIRED)
    public void init() {
        Session session = getSession();
        StopWatch stopWatch = new StopWatch("Insert test");

        stopWatch.start("Saving entities");
        for (int x = 0; x<NUMBER_OF_ENTITIES; x++) {

            PersonEntity ent = new PersonEntity();
            double rand = Math.random();
            ent.setId(new Long(System.currentTimeMillis() + x).hashCode());
            ent.setFName(""+ rand);
            ent.setLName("" + rand);
            ent.setAge((int) (rand * 100));
            session.persist(ent);
            if (x%BATCH_SIZE == 0) {
                session.flush();
                session.clear(); //<-- IMPORTANT TO CLEAR THE SESSION
            }
        }
        stopWatch.stop();
        System.out.println(stopWatch.prettyPrint());
    }

}

There is something subtle about this code that I want to talk about. Firstly notice that the inserts are in one transaction - although I can use the hibernate session to being and commit a transaction I am instead using the @Transaction spring annotation. The corresponding configuration (since I am using Jboss I can tie this in with the Jta transaction manager) is the following: 

    <!-- configure JTA transaction manager -->
    <tx:annotation-driven transaction-manager="transactionManager" />
    <bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
    </bean>

Since spring works by generating a proxy for this class I am also implementing an interface (its good practice anyway). The other thing are the periodic calls to session.clear() and session.flush() - they are to prevent an OutOfMemroyException which can occurr if you are inserting a large amount of objects.  

Here is the output of the program:

StopWatch 'Insert test': running time (millis) = 4687

-----------------------------------------
ms     %     Task name
-----------------------------------------
04687  100%  Saving entities

The performance is no different from vanilla JDBC batching because underneath the hood its using the same mechanism. There is however a drawback you cannot use oracle natvie bindings which speeds up batch inserts by 1.5x.

Apple care is useless

I just got off the phone with the apple care folks. I cannot believe how ignorant and absolutely useless it really is, specially given the fact that apple charges $350 for a three year support. I wanted to set some user environment variables and was surprised to see there was no GUI in the mac to configure them. 

I have recently moved to the mac and was surprised not to find the conventional .bashrc file in the user home directory either. I mucked around the internet for a while and spent some time on the apple support website. So I decided to give apple care a shot. Gave them a call and was surprised to get through to a customer support representative within a couple of minutes. I told the guy that I wanted to add some user environment variables and he had no idea what environment variables were. I explained to him what they were and that I needed them to do some java development.

He forwarded me a customer support specialist who informed me that they dont support “configuration via the terminal”. I was making a case that this is one of the most elementry configuration changes you can make to system - when the phone got cut. They had my phone number so I waited for five minutes to see if I would get a call back - no one called. 

So I called up again after spending time with a customer support agent I was again forwarded to a customer support specialist. She too had no idea about environment variables and was surprised why someone would use the terminal. She put me on hold for five minutes and told me that they “did not support” such modifications, and that if I wanted to do development I was on my own. By this time I was sure I was not going to get any help from the team that claims to support people moving to a mac from other operating systems. 

I looked up the internet one more time and figured out that creating a ~/.profile file would do the trick. Bash picks it up before launching the shell. I have since then happily installed groovy, grails and ant and am happy with my mac experience. However I am a little surprised at just how bad a “paid” service can be. $350 for three years to help people navigate around the pre installed GUI is not worth it. Thank God I did not buy it - I recommend you don’t either.

Debugging grails in IntelliJ Idea with acegi plugin

module settings for debugging grails applications

module settings for debugging grails applications

I am liking IntelliJ more and more every day. So after weeks of just  using intelliJ for Grails without using the debugger I was finally stuck at a point where I just had to inspect a few varriables to debug a problem. So I fired up the debugger. Getting the debugger started on simple Grails applications works like a charm.

The problem happens when you have a slightly more complex configuration and have a lot of plugins. For example I was using the acegi plugin and the applicaiton failed to pick up the jars in the plugins/acegi-x/lib folder. I had to add them manually to the module libs. The other little nigling thing was that the plugins/xxx/src folders were not included in the src path. You have to add them manually. Not too bad - but clicking on the debug button will still give you build failures.

Inside the src/ folder of the acegi plugin sits a folder called template which is not a src file at all its a gsp styled template. I think the plugin internally uses it to generate the domain classes during plugin installation. This folder has to be mannually excluded from the module src path.

Once you have done this - bingo, the debugger works beautifully.

RIAs using Flex 3 - first impressions

flex

flex

My first experience with Adobe Flash (back then Macromedia) was back in 2001-02 when I was attempting to open a web animation start up while still in school. Needless to say the startup went no where but I was introduced to a really cool technology. Of course back then flash was no more than web animation tool and using flash maker was more akin to a movie software with timelines, layers and a quite sophisticated vector graphics drawing toolkit. I have always admired both Macromedia and Adobe for the wonderful tools that they put out, fireworks, dreamweaver, director, photoshop - the list is full of stellar tools. I was expecting nothing less from flex an ecosystem for RIA development.

Flex is basically a client side framework for developing awesome web application UIs running in Flash, this does limit you to linux, windows and Mac clients only (someone running Solaris on their machines will not be able to run your apps). Flex takes this concept a step further and enables you to develop applications that can be deployed as thick clients using Adobe AIR. At it’s guts its a bunch of action script libraries for remote service consumption, a library of interactive components and a compiler that compiles XML markup to a swf file of well laid out components ready to be shown in the browser.

The tool of choice for flex application development is Flex Builder from Adobe. Not surprisingly Adobe does not give this away free - the flex SDK is free under MPL however. For all practical purposes any serious web applications and developers should pay for the flex builder license and use the tool, I think its well worth the money. Flex builder is built on top of the eclipse rich client platform and is also distributed as a plugin for eclipse (they cost the same). Flex builder is distributed only for windows and mac. After using tons of open source eclipse plugins. it’s great to use a polished, functional, well written tool. It’s great. The source editor is great for MXML and AS editing, auto completion works flawlessly for custom components and written class files. Debugger works rather well (although I would like to see the code evaluation feature, the eclipse “display” window for java debugging has simply spoilt me). The drill downs and context help is great. I can say without a doubt that if you plan to serious flex applicatoin development, flex builder will be well worth the money spent.

From a framework’s perspective flex is an event driven, component oriented framework  that provides layout, arrangement and remoting facilities. The entire flex app is composed of individual components, customized via their attributes. The application is coded in an XML markup (MXML) and coding it seems vaguely similar to JSF. What absolutely blew me away was how intuitive custom component development was and how nicely it integrates into the flex builder. For example, if you wanted to create a new component all you have to do create a new MXML file and point to the folder using “xmlns” in the main application mxml file. Thats it flex builder’s auto complete and even the drag and drop designer will be working with your components. Generating custom events is equally simple. It’s quite awesome to see a well thought out architecture like this, since it helps you code your application in a more systematic and orderly fashion.

flex builder

flex builder

Next was the sheer simplicity of implementing drag and drop in flex applications. List based components, like data grid, lists and trees can implement drag and drop by simply modifying a few attributes. Another thing  is the inbuilt concept of states and transitions between states with browser back button integrations, a phenomenal abstraction. Hand coding an ajax based application involves a lot of plumbing code to work like this. There are few other features that I liked. Firstly the E4X XML support for XML. Action script has built in support for XML parsing. Navigating/iterating arbitrary XML structures is super siimple with using XPath like syntax. Secondly the concepts of grids and anchor constraints is simply awesome. Layout on reisize and cross browser CSS simply works.

The integration with server side logic is also well supported. Consumption of both restful and conventional web services is built into flex. Java developers have an added option of using AMF (action script message format) - a binary representation of AS objects in conjunction of bazeDS or LCDS. Setting up and configuring blazeDS is super easy and it gives really easy server-client messaging (with server side push) and remoting facility. The only down side is that you have to write both the java and action script data transfer objects.The flex SDK also comes with an ant taskdef, integration with java build cycles becomes quite easy.

All in all a fanstanstic alternative for RIA’s, I am already aware of one high traffic website using flex - yahoo maps. Going forward I see this framework used in a variety of different web applications, specially involving data visualization and complex workflows. I am also trying to use it for a new application at work, lets see how it goes, so far I am very impressed.

Trasparent remoting using Spring HTTP invoker with Acegi Security

I was investigating remoting for an enterprise java application. Since this was a vanilla tomcat application on Spring I had the following choices:
1. XML RPC
2. RMI
3. Spring HTTP invoker
4. Burlap

For reasons I don’t want to elaborate here I decided to use Spring HTTP invoker. The next step was to integrate this with spring.
The proces is quite straight forward.
First wrap your service in a HttpInvokerServiceExporter

<bean name="/wowservice" class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">
<property name="service" ref="wowservice"/>
<property name="serviceInterface" value="test.WowService"/>
</bean>

Next consume it at the client using:

<bean id="httpInvokerProxy" class="org.springframework.remoting.httpinvoker.H
ttpInvokerProxyFactoryBean">
<property name="serviceUrl" value="http://xyz:8080/remoting/wowService"/>
<property name="serviceInterface" value="test.WowService"/>
</bean>

Simple enough now you can start to consume this service - directly.

But here is the really awesome thing. Acegi security integrates very well with Spring.

All you have to do is this:
1. Enable the basic auth filter in the Acegi configuraiton
2. Modify your client configuration to make use of the HttpInvokerRequestExecutor property and write an extension to SimpleHttpInvokerRequestExecutor and encode the username:password as base 64 - This can be done by modifying the client configuraiton and adding the following line:

<property name="httpInvokerRequestExecutor"><ref bean="httpInvokerReque
stExecutor"/></property>

to the bean definition of the httpInvokerProxy definition.

To get the encoding correct I simply made use of AuthenticationSimpleHttpInvokerRequestExecutor and it works quite well.

Here is a simple custom executor that simply updates the request with HTTP auth information for every API call. An authentication object is a wrapper class for the username and password that is injected into the executor using Spring.


package com.pranayahlawat.client;

import java.net.HttpURLConnection;

import org.apache.commons.codec.binary.Base64;
import org.springframework.remoting.httpinvoker.SimpleHttpInvokerRequestExecutor;

public class AuthenticationExecutor extends SimpleHttpInvokerRequestExecutor {

private Authentication authentication;

protected void prepareConnection(HttpURLConnection con, int contentLength)
throws java.io.IOException {
super.prepareConnection(con, contentLength);

if (authentication == null)
throw new RuntimeException(”Cannot prepare connection without an authentication object”);

String base64 = authentication.getUsername() + “:” + authentication.getPassword();
con.setRequestProperty(”Authorization”, “Basic ”
+ new String(Base64.encodeBase64(base64.getBytes())));

}

public Authentication getAuthentication() {
return authentication;
}

public void setAuthentication(Authentication authentication) {
this.authentication = authentication;
}
}