Thursday, May 27, 2010

Java Wildcards Vs. Generics...

I have never used wildcards in java until i read this.

Let's say I have a super class Vehicle and few sub classes like Scooter, Bike, Car, etc... Now I need to have a list of vehicles, my first thought would be something like:

 List<Vehicle> lstVehicles;

Instead, some people are recommending something like:

 List<? extends Vehicle> lstVehicles;

Why should I use wildcards instead of simple generics?

Because Java generics are invariant.

Suppose we have B extends A:

* B is a subtype of A
* an instanceof B is also an instanceof A

Since Java arrays are covariant:

* B[] is a subtype of A[]
* an instanceof B[] is also an instanceof A[]

However, Java generics are invariant:

* List<B> is NOT a subtype of List<A>
* a instanceof List<B> is NOT an instanceof List<A>.

Wildcards are used to make it more flexible while preserving type safety.

*
List<B> is a List<? extends A> 

References:
Wildcards
Generics
Generics and subtyping
More fun with wildcards

Friday, May 21, 2010

Java String manipulation: Appending empty string to 'var.subString(x,y)' saves memory...


In java usually we do SubString operation as follows.


    String strMainData = "Some long String..." ;
    String strSub= strMainData.subString(i,j); // Where i and j are index values...

This operation will keep the reference to same object strMainData,but only returns smaller string as per the indexes. So it uses same memory as the original String.

We should use it as follows.

    String strSub = new String(strMainData.subString(i,j));
OR

    String strSub = strMainData.subString(i,j) +"";
This will only keep the reference to new smaller String and removes reference to original String variable.



Singleton refactored:Initialization on demand holder idiom...

Hey guys, check this out. I found this while searching around different styles for singleton pattern. It basically provides on demand loading of the instance.

public class Something {
 private Something() {
 } 
 private static class LazyHolder {
  private static final Something INSTANCE = new Something();
 } 
 public static Something getInstance() {
  return LazyHolder.INSTANCE;
 }
}

The static class LazyHolder is only executed when the static method getInstance is invoked on the class Something, and the first time this happens the JVM will load and initialize the LazyHolder class. The initialization of the LazyHolder class results in static variable INSTANCE being initialized by executing the (private) constructor for the outer class Something.

More @ Wiki

Hibernate : One-to-many Parent-Child relationships...

Hibernate is quite good ORM framework. When we need one-to-many relationship in hibernate, we need to take ArrayList or Set. If the structure is kind of tree, then hibernate can perform wired if not properly tweaked.


Basically if you are having some sort of many to one relationships structure from child to parent. In hibernate all depends on mapping. Tweak your mapping, Use One-to-many relationship from parent to child using java.util.Set.


Do not use ArrayList because List is ordered, so hibernate will add extra column for that ordering only.
Also check your lazy property. If you load parent and you have set lazy="false" on its child set property (variable which is of type Set), then all of its children will be loaded from DB which can affect the performance.


Also check 'inverse' property for children. If inverse is true in child table, that means you can manage the child entity separately. Otherwise you have to do that using the parent only.

Thursday, May 20, 2010

AXIS2 web service client - without sub/proxy ...

This article is regarding how to call an web service without modifying the client each time for diff. web service OR method call. Basically we use stub/proxy classes for diff. web service method calls using Axis2, but internelly it calls using XML SOAP envelopes. So, we can direcftly convert the client to use Axis2 API classes and provide an implementation which only needs to handle the response from the call. Response will be in XML format,so we need to fetch data from XML. We can covnert XML into Pojos using Castor or JAXB libs.

You can directly use ServiceClient class to call web service, which provides call using XML only and returns XML response. For different methods of web service, you have to convert the XML response to some java POJO to use it. Only Response handling needs to be done at your end. that you can do like from XML to Map etc...

So you won't need any other stub classes to call any web service, only needs to handle response XML or converted POJO.

This is the way you don't need to modify your client every time for diff. web services. You can develop like providing a response handler to client externally. So that for every different web service you will have diff. response handler class which is implementation of you interface.

//common interface for response handlers...
//implement this for diff. web service/methods

public interface WSRespHandler{
    public Object getMeResp(Object respData);
}

//pass particular handler to client when you call some WS
public class WebServiceClient {
    public Object getResp(WSRespHandler respHandler) {
        ...
        return repHandler.getMeResp(xmlData);
    }
}

References:

http://www.developer.com/java/web/article.php/3863416/Using-Axis2-and-Java-for-Asynchronous-Web-Service-Invocation-on-the-Client-Side.htm

http://www.devdaily.com/blog/post/java/java-web-service-client-read-array-list/

Facebook integration in your web application...

This is not regarding only java, you can do this on any web application in different languages also.

Facebook is getting popular now a days. Almost every site has facebook login enabled, so that if the user has facebook account he can login using that and can use the site as a registered user. For this the user must allow the site to use his facebook user data (Friends list, profile details etc...). Facebook provides different set of APIs to do such integration with your site.
 
It basically provides different client APIs which are based on different technologies lke PHP, Java, Javascript etc.. Here i will show you how to integrate facebook only using javascript API, which is the best way to do this.
 
    1. First step is, you have to include the javascript from FB as follows.  

        <script type="text/javascript"
        src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php"></script>
 
    2. You have to init the Facebook JS library with you facebook API key and provide the XDReceiver url. XDReceiver.htm is provided by facebook which is to be uploaded on you server to handle the callback to Facebook's javascript functions. It will store facebook cookies on your server so that you can access the facebook session in your site to fetch facebook data for the logged in user.    

        FB.init("myApiKey","/html/xd_receiver.htm", {
        "doNotUseCachedConnectState" : false
        ,"reloadIfSessionStateChanged" : true    //Reloads the page if user logs in OR out
        ,"ifUserConnected" : showFacebookInviteLink()    //Is user connects to FB, executes the provided JS function          
        });
 
    3. Now you need to call function which will provide the facebook login popup for user. User can login into facebook and then allows the application to use his/her data.
   

        FB.Connect.requireSession(); // This will give the popup to login
      
        // This will check if FB is initiated with application key and user logged in or not. On user session, it will executes the function.
        FB.ensureInit(function() {
            FB.Facebook.get_sessionState().waitUntilReady(
                    function() {
                        
            });
          
        });
 
    4. To logout from Facebook, you just need to call JS function FB.Connect.logout();

    Now you can access different functions of the FB JS library to acces any data it supports to use on your site/application having session initiated.I will show how to show invite friends popup dialog on your site/application. Call the below function on invite button/link click event.
   

       function inviteFacebookFriends() {      
        FB.ensureInit(function() {
            FB.Facebook.get_sessionState().waitUntilReady(
                function() { //on Connect succes
                        var fbml = "";
                        fbml = '<fb:fbml>\n'
                                + '<fb:request-form\n'
                                //Redirect back to this page                           
                                + ' action="'+document.location+'"\n'                           
                                + ' method="POST"\n'
                                + ' invite="true"\n'
                                + ' type="app test invite"\n'
                                + ' content="app test inviting...\n'                           
                                + '
                                + ' label=\'Join me!\' />"\n'
                                + '>\n'           
                                + ' <fb:multi-friend-selector\n'
                                + ' rows="2"\n'
                                + ' cols="4"\n'
                                + ' bypass="Cancel"\n'
                                + ' showborder="false"\n'   
                                + ' exclude_ids="excludeIds"\n'           
                                + ' actiontext="Use this form to invite your friends to connect to my site."/>\n'
                                + ' </fb:request-form>' + ' </fb:fbml>';
                      
                        var dialog = new FB.UI.FBMLPopupDialog("Invite Friends To This Site",fbml);                                      
                        dialog.setContentWidth(650);
                        //dialog.setContentHeight(450);
                        dialog.show();
            });
        });  
    }
     
Thats it! This will show the standard popup dialog for friends invitation. Basically this FBMl will be rendered by facebook js API.Now user can select any of his friends and send them invitation to join your site. Let me know if you have any queries OR problems, will try to help around.