Monday, June 20, 2011

Eclipse is becoming increasingly annoying

As an Android developer I find Eclipse these days is becoming very unreliable. All of a sudden all my projects would not compile. I tried doing a project-> clean and build but still the error console would not tell me what is wrong. I had not made changes to any of the files. The only message I got was "Your project has errors, please fix it before trying the build".. very helpful right. The I thought let me try using my favorite IDE for all these years Netbeans, I have not done any Android projects using this super hero so a 30 sec googling is all that took to setup the environment and I imported my projects and there it is the proper error message your " Debug Certificate expired on 6/18/11 11:25 PM". Thank you netbeans you are amazing.

Thursday, December 23, 2010

Parcelable interface in android

The most efficient way to pass custom objects between android activities in by implementing the Parcelable interface. Two methods describeContents and writeToParcel needs to be overridden

public class MyParcel implements Parcelable{
private String name;
private List emails;

public int describeContents() {
// TODO Auto-generated method stub
return 0;

public void writeToParcel(Parcel dest, int arg1) {

Bundle bundle = new Bundle();
bundle.putParcelableArrayList("emails", emails);


In this example MyParcel class has a name and a list of emails which we would like write to a parcel so that other activities can have access to it. As you can see the basic java types have their corresponding write methods to write a user defined class or a list we first create a bundle and then write it to the parcel.

Tuesday, December 21, 2010

Exposing Spring beans as a JMX managed bean

I had a few Spring service beans that I wanted to expose as a JMX bean. I was using annotation to define my Spring beans and the steps are really straight forward to expose these as a JMX managed bean using the support from spring. Spring 2.5 and 3.0 comes shipped with some easy annotations to do this. First you define the spring exporter for managed resource.

<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter" lazy-init="false">
<property name="autodetect" value="true"></property>
<property name="namingStrategy" ref="namingStrategy"></property>
<property name="assembler" ref="assembler"></property>
<property name="beans">
<entry key="bean:name=myManagedBean" value-ref="myService"/>

<bean id="attributeSource" class="org.springframework.jmx.export.annotation.AnnotationJmxAttributeSource"/>
<bean id="assembler" class="org.springframework.jmx.export.assembler.MetadataMBeanInfoAssembler">
<property name="attributeSource" ref="attributeSource"/>
<bean id="namingStrategy" class="org.springframework.jmx.export.naming.MetadataNamingStrategy">
<property name="attributeSource" ref="attributeSource"/>

The exporter bean needs to have lazy-init flag set to false, this flag when set does not call the init code when the bean is loaded. The attributeSource bean indicates that we are going to use annotation to expose the bean attributes. And finally the namingStrategy bean defines how the managed beans are named and accessible in the jconsole. Once these beans are defined in the spring context now we are ready to code the managed resource.

@ManagedResource(objectName = "bean:name=myManagedBean", description = "Asample")
public class MyServiceImpl implements MyService {

private Integer myManagedAttribute;

@ManagedAttribute(description="The bean Attribute")
public void setMyManagedAttribute(Integer val){
@ManagedAttribute(description="The bean Attribute")
public Integer getMyManagedAttribute(){
return myManagedAttribute;
@ManagedOperation(description="the operation that is exposed")
public void myOperation(){

In the example which is a Spring service we can also make it a managed resources by adding the managedResource annotation the objectName given here should be the same that was given in the exporter bean key. Then every get or set method can be annotated with managedAttribute and other methods can be annotated with managedOperation.

Array Copy using Generics

If you look at the method definition of copy in the collections framework it looks something like this.

public static <T> void copy(List< ? super T > to, List <? extends T> from)

The ? in generics means wild card i.e. In this case any class or interface that is a super class of T for the first parameter or extends T as in the second parameter. An important concept that one should understand in this example is covariance. Arrays in java are covariance i.e. if Integer extends Number then Interger[] also extends Number[]. This is not the case when it comes to generic lists where List<Integer> is not a sub class of List<Number>. With this basic understanding lets simplify the above method definition and see what happens

public static <T> void copy(List<T> to, List <T> from)

Now let us call the method as follows.

List<Object> objs = Arrays.<Object>asList("San","John",1042);
List<Integer> ints = Arrays.<Integer>asList(10,20);
TestClass.<Object>copy(objs, ints); // Call(1)
TestClass.<Integer>copy(objs,ints); // Call (2)
TestClass.<Number>copy(objs,ints); // Call (3)

If the rule of covariance is applied then all three calls are not legal. as List<Integer> is not a subclass of List<Object> if you consider call (1) To make call (1) legal the declaration should be modified to

public static <T> void copy(List<T> to, List <? extends T> from)

With this method declaration call (1) is legal but how about (2) and (3) they are still not legal as List<Object> is not a subclass of List<Integer> for the "to" parameter same concept is applicable for call (3) and because of this we end up having public static <T> void copy(List< ? super T > to, List <? extends T> from) which is the most suitable for all calls. I would recommend reading the Java Generics and Collections by Maurice Naftalin to understand more about Generics in Java.

Wednesday, December 8, 2010

Spring security LDAP authentication

I was experimenting on spring security and found that with spring 2.5 LDAP authentication was a pain. This is what I did to get around the issue.

First my maven POM had these dependencies




Your web.xml should have the contextConfigLocation which refers to the location of the spring security config xml file, the spring web context loader and the spring security filter.

<!-- Spring context loader servlet and listener class need to spring managed beans-->
<listener-class> org.springframework.web.context.request.RequestContextListener </listener-class>

<servlet-class>org.springframework.web.context.ContextLoaderServlet </servlet-class>

<!--spring security filter chain -->



The contents of context-security.xml is as follows

<!-- first configure the LDAP url -->

<ldap-server id="appLdapServer" url="ldap://,o=ME" />

<!-- configure the LDAP authentication provider here you can specify search filters
which will start the LDAP search from a given node in the tree. you can also specify
users with certain specific attributes so that only those users can have access to your application web page

<ldap-authentication-provider server-ref="appLdapServer"
user-search-filter="(cn={0})" group-role-attribute="ou=Engineering"
user-search-base="ou=Software Eng"/>

Now the http intercept url xml elements need to be written for this we shall have a simple rule which shows pages in folder inbox if the user has been authenticated otherwise the user gets redirected to login or error page in folder auth so make sure you have only unsecure pages in the auth folder.

<http access-denied-page="/auth/denied.html">
access="ROLE_ANONYMOUS" />
authentication-failure-url="/auth/login.html" />
<logout logout-url="/auth/logout.html"
logout-success-url="/" />
<anonymous username="guest" granted-authority="ROLE_ANONYMOUS"/>

The IS_AUTHENTICATED_FULLY is a spring security access constant which does the trick to all pages inside inbox to be visible if the LDAP authentication is successful

Tuesday, December 29, 2009

Credit card validator in JSF

If you have a JSF page with credit card information you might want to validate the credit card number the user is entering. Different credit card companies (VISA,Master & Amex) have credit card numbers that follow different validation rules. All major credit cards will satisfy a Cyclic Redundancy Check (CRC) called Luhn Algorithm.

Luhn Algorithm

Step1: Sum all odd digits of the credit card number
Step2: Take each even digit multiply it by 2 if the result is greater than 9 subtract 9 from it then add it to the Sum of Step1
Step3: If sum is divisible by 10 then CRC passed else failed

To implement this lets do the following
1.In your JSP page which has the credit card form add the validator to the the card number input text field

<h:inputText label="Credit Card Number:"
id="inpCCnumber" required="true"
<f:validator validatorId="CreditCardValidator"/>

As you can see the custom credit card validator is called CreditCardValidator. The value is stored in the backing_ccbean. Assume there is a drop down list from which the user selects the card type(Visa,Master or Amex) and this value is stored in the same backing bean backing_ccbean in the attribute cardType, however this value will be set to the model object only after the validation phase so we need to directly bind to the component

<h:selectOneListBox label="Credit card type" value="#{backing_ccbean.cardType}"
<f:selectItem itemValue="1" itemLabel="Visa" />
<f:selectItem itemValue="2" itemLabel="Master Card" />
<f:selectItem itemValue="3" itemLabel="American Express" />

backing_requestscope.cardTypeChoice maps to a javax.faces.component.html.HtmlSelectOneListBox this way we get the users selection in the validation phase of the JSF life cycle.

2. The next step would be to define CreditCardValidator in faces-config.xml. Add the following XML element to your faces-config


The XML element is simple there is an ID and a Class we have called it MyCreditCardValidator.

3. Now let us write the java class MyCreditCardValidator in the package validators

package validators;

public class MyCreditCardValidator implements javax.faces.validator.Validator{

public void validate(FacesContext ctx,UIComponent component,Object value) throws ValidatorException{
String ccnum=(String)value;
// get the card type form the binding object instead of the model object
HtmlSelectOneListBox cardChoiceComp= (HtmlSelectOneListBox) context.getApplication().createValueBinding("#{backing_requestscope.cardTypeChoice}").getValue(context);
int cardType = ((Integer)cardChoiceComp.getValue()).intValue();

boolean validCard = validateCard(ccnum,cardType);

if (validCard==false) throw new ValidatorException(new FacesMessage(" Invalid credit card format!!!!"));


private boolean validateCard(String ccnum,int cardType){
// visa cards always start with 4 and are either 13 or 16 digits in length
final int VISA=1;
// master cards are 16 digits in length and the first 2 digits range from 51 to 55
final int MASTER=2;
// Amex cards are 15 digits in length and the first 2 digits range from 34 to 37
final int AMEX=3;
switch(type) {
case VISA:
if ((ccnum.length() != 13 && ccnum.length() != 16) ||
return false;
case MASTER:
if (ccnum.length() != 16 ||
Integer.parseInt(ccnum.substring(0,2)) <> 55)
return false;
case AMEX:
if (ccnum.length() != 15 ||
(Integer.parseInt(ccnum.substring(0,2)) != 34 &&
Integer.parseInt(ccnum.substring(0,2))) != 37))
return false;

// luhn validate
char[] charArr = ccnum.toCharArray();
int[] num = new int[charArr.length];
int total =0;
for(int i=0;i -1; i--){
if (alternate){ // multiply each even digit by 2 then add it to total
num[i] *=2;
if (num[i] > 9) num[i] -=9;
total +=num[i];
alternate = !alternate;

if (total % 10 != 0) return false;

return true;



In the MyCreditCardValidator class the most important thing to notice is how the value of card type is got since the validate method is called in the validation phase of a JSF life cycle the model objects are not set with the value hence the only way to get the value of a component other than the component that is being validated is thru the component binding.

Tuesday, December 22, 2009

Rollback JMS transactions in MDB Vs MDP

If you are writing an application which has a message driven bean or a message driven POJO you might want to put back the message in JMS destination if there is an exception in your application logic. In other words rollback the JMS transaction if there is an exception in onMessage. On a side note the acknowledgement mode of the message is considered to be AUTO_ACKNOWLEDGE instead of CLIENT_ACKNOWLEDGE as in the AUTO mode the messages are automatically removed from the queue unless a rollback is issue. Let us discuss how to issue a rollback in the case of an MDB first and then in a MDP.

Issuing a rollback in a Message Driven Bean (MDB)

A sample MDB implements MessageDrivenBean and MessageListener as follows

public class ExampleMDB implements javax.ejb.MessageDrivenBean, javax.jms.MessageListener{

javax.ejb.MessageDrivenContext context;

public void setMessageDrivenContext(javax.ejb.MessageDrivenContext aContext) {
context = aContext;
// ejbCreate and ejbRemove methods go hear.

// onMessage needs to be implemented here
public void onMessage(javax.jms.Message inMessage) {

// do your business logic here
// if error in business logic rollback by calling



The message driven context is set by the container in a container managed bean. The rollback is achieved by calling the context.setRollbackOnly() when this happens the message is put back in the queue. One should be carefull as the onMessage will be called repeatedly until the processing is fine and the rollback is not issued.

Issuing a rollback in a Message Driven POJO (MDP)

In a Spring MDP the task of issuing a rollback is as straightforward as just throwing a RunTimeException.

public class ExampleMDP implements javax.jms.MessageListener{

public void onMessage(Message message) throws RuntimeException{

// if error in business logic throw a RuntimeException

When the MDP is configured in the application context xml file make sure it is sessionTransacted, by setting it's value to true. Refer to my earlier article