Tuesday, September 7, 2010

Liferay Struts Portlet: Usage of SessionErrors class...

This is very common issues we come across when we want to change portal code with extension environment. Mostly we do is, copying the code from portal to ext and making new struts portlet.

And for sending errors to pages, we use SessionErrors.add(...) method, which will eventually forward to default error.jsp file. So you will never find what is happening. Simple thing, to make this working fine, is...

- Make new empty page named error.jsp in your portlet.
- Make new Struts-config and tiles-def entry of your new JSP in ext.
- From your render method, forward to the new file when you have SessionErrors filled with errors like,

 if (!SessionErrors.isEmpty(req)) {
  return mapping.findForward("portlet.portlet_name.error");
 }
 

See this link to understand the detailed problem...

Friday, August 20, 2010

Liferay Wrapper Plugins ...

Very nice article about liferay core functionality extension. You can create wrappers around core services and it will be in service when you compile-deploy it! Isn't that's great? Check the link.

Tuesday, August 3, 2010

Some Useful Linux commands while deploying...


While deploying any WAR in tomcat on Linux platform, most problem we have faced is Linux terminal commands. In all industries you will mostly have a Linux server for test server,staging server etc...So most of the times developers need to test the code locally and then deploy it in centralized test OR development server where other can access and test it.

The steps will be same for all programmers. We get an email from so called IT people with deployment instruction having IP, username ,password (Which is always weird and we always copy paste it :)) etc... We Linux into the server using Putty or some other terminal client. But most of windows developers will face problem here. So some commands which are very easy to remember are,

- cd (Same as windows)
- pwd (Shows current working dir)
- ./ (this folowing with script filename, will execute the script. You can also use 'su')
- ps ax (Shows running process details, with process ID. like windows task manager shows.)
- grep hi (Finds the string 'hi')
- kill -9 567 (Kills process with ID 567)

Now in Linux if you have many servers running and you want to stop only specific one then you can use following combination,
- ps ax|grep projDir (This will show the process having projDir in sys variable.)

After that we can kill that process easily.

Before running startup.sh you must have set variable for JAVA_HOME, so that tomcat can find the java env.

There are other commands which are for changing file permissions (Read only, executable etc...) but will post it later.

-- Update By Kunal --
- scp sourcepath user@destserverhost:destpath (Secure copy of file from one linux server to another)

Example

scp /root/example.html root@66.235.111.88:/home/example

Wednesday, June 9, 2010

Liefray: Using JSONObject for Ajax in Plugin Portlet...

Many times we face situations when we need to use Ajax call from JSP pages. Using jQuery, its very easy to call any JSP through AJAX. You can just call the JSP and show its response from callback into some DOM element.

 $.ajax({  
      type: 'POST',  
      url: getUrl(),  
      data: {},                                   
      success: function(returnData) {  
          $('#someElementId').html(returnData);  
      }  
     });  

But this is useful when you want some big data OR some complex UI layout which is hard to generate using callback javascript function. Simple we call the JSP in which we have already designed the layout properly so we don't need to bother about manipulating the returnData in javascript.

Now think if you only need some small amount of data from server side, how will go? Making a new JSP for such a small task is not worhty i think. One technology is there for our help,JSON. JSON is a simple string notation of any object, which represents key-value pair like hashmap but uses its own structure to define objects.

Liferay provides com.liferay.portal.struts.JSONAction class which is a struts Action class. But to use this one in portlet we need to configure the portlet as a com.liferay.portlet. But there is one more way to use JSON with plugin portlet, using overriding serveResource method from GenericPortlet class into your portlet class.

 protected void getSomeDataAsJson(ResourceRequest request, ResourceResponse response)  
 throws PortletException, IOException {  
     String myParam = ParamUtil.getString(request, "myParam","");  
     // Some service call using params from request...  
     Obj obj = getDataFromSomeService(myParam);  
     JSONObject jsonObj = JSONFactoryUtil.createJSONObject();  
     // obj can be anything... Integer,Boolean,String or some custom POJO...  
     jsonObj.put("testData", obj);  
     OutputStream os = response.getPortletOutputStream();  
     try {  
         os.write(jsonObj.toString().getBytes());  
     }  
     finally {  
         os.close();  
     }  
 }  
 @Override  
 public void serveResource(ResourceRequest request, ResourceResponse response)  
         throws PortletException, IOException {  
     String cmd = ParamUtil.getString(request,Constants.CMD);  
     if ("getSomeDataAsJson".equals(cmd)) {  
         getSomeDataAsJson(request, response);  
     }  
 }  

The above method will provide the JSON object as a result in javascript callback function. Check the Ajax call,

 $("input:button[@name='<portlet:namespace />SomeThing']").click (function() {  
     $('#<portlet:namespace />myDiv').text("");  
     //URL which goes to your portlet...  
     var url = "<portlet:resourceURL><portlet:param name='<%=Constants.CMD %>' value='getSomeDataAsJson' /></portlet:resourceURL>";      
     //Append your hidden input fields in the resourceURL...   
     url +="&"+$('input:hidden').serialize();   
     $.ajax({  
             url: url,  
             data: {},  
             dataType: 'json',  
             success: function(message) {  
                     $('#<portlet:namespace />myDiv').text(message.testData);  
                     }  
             }  
         );      
     });  

This way we don't need to create JSPs for small data fetching. Show other ways also using simple AJAX calling (Like DWR supports, direct calling JAVA class method from JS and returns data in JS callback).

Wednesday, June 2, 2010

jQuery - usage of $.bind method...

jQuery is widely used javascript library which provides easy ways to do complex things. By using simple Javscript, it takes too much time to code it, but jQuery simple it down to few lines.

To check multiple Checkboxes, i have written the following code.

 <script type="text/javascript" src="html/js/jquery.js"></script>  
 <script type="text/javascript">  
 //on load, register events for checkboxes...  
 $(document).ready(  
      function() {       
           $('#chk_all').change(checkAll);            
           $('form[@name="fm"] input:checkbox[@name!="chk_all"]').each (function(index) {  
                $(this).change(selectForDelete);  
           });  
      }  
 );  
 function checkAll(){  
      var isCheck = this.checked;  
      $('form[@name="fm"] input:checkbox[@name!="chk_all"]').each(function(){  
           this.checked = isCheck;  
           $(this).trigger("change");  
      });  
 }  
 function selectForDelete(){  
      var alertIdsObj = $('form[@name="fm"] input[@name="deleteIds"]');  
      if (this.checked) {  
           if (alertIdsObj.val().indexOf(this.value)==-1) {  
                if(alertIdsObj.val()=='') {  
                     alertIdsObj.val(''+this.value);  
                } else {  
                     alertIdsObj.val(alertIdsObj.val()+","+this.value);  
                }  
           }  
      } else {  
           if (alertIdsObj.val().indexOf(this.value)>=0) {  
                alertIdsObj.val(alertIdsObj.val().replace(this.value+',',''));  
                alertIdsObj.val(alertIdsObj.val().replace(','+this.value,''));  
                alertIdsObj.val(alertIdsObj.val().replace(this.value,''));  
           }  
      }  
 }  
 //Function called for item details...  
 function viewAlertDetails(alertId) {  
           $.ajax({  
            type: 'POST',  
            url: getUrl()+"&alertId="+alertId+"&cmd=detailed-market-alerts",  
            data: {},                                           
            success: function(returnData) {  
                 $('#-mainDiv').hide();  
                 $('#-detailsDiv').html(returnData);  
                 $('#-detailsDiv').show();       
            }  
           });       
 }  
 function getUrl() {  
      var url = new String(document.location);  
      var index = url.indexOf("?");  
      if (index!=-1) {  
           url = url.substring(0,index);  
      }  
      return url;  
 }  
 //function called from second page to go back to first page with latest data...  
 //Repalces the old content with new  
 function viewAlerts() {  
      $.ajax({  
            type: 'POST',  
            url: getUrl(),  
            data: {},                                           
            success: function(returnData) {       
                var myData = $(returnData).find('#-mainDiv').html();  
                $('#-mainDiv').html(myData);  
                $('#chk_all').bind('change', checkAll);  
                $('form[@name="fm"] input:checkbox[@name!="chk_all"]').each (function(index) {            
                     $(this).bind('change',selectForDelete);            
                });  
                $('#-detailsDiv').html("");  
                $('#-detailsDiv').hide();  
                $('#-mainDiv').show();  
                return true;  
            }  
           });       
      return false;  
 }  
 </script>  

The flow is as below,
- First page shows list of data.
- By clicking particular item from the list, i hides the mainDiv and shows details of the item in detailsDiv using $.ajax.
- By clicking "Back" button from detailsDiv, i again loads the main page using $.ajax.

The problem is, when i go to second page and comes on the first page using $.ajax,i change the HTML content of mainDiv with the latest data in viewAlerts() javascript function as $('#-mainDiv').html(myData);.

If you check the script, you will notice that i have registered the event handling for checkboxes in the document,One for main checkbox and one for all other checkboxes of the list, using $(document).ready() jQuery function. Event handling works fine at first page. But when we change the html content of the div afterwards, event handler automatically removed.

So to re-enable the events on checkboxes,we need to use following code in viewAlerts() javascript function.

 $('#chk_all').bind('change', checkAll);  
 $('form[@name="fm"] input:checkbox[@name!="chk_all"]').each (function(index) {  
      $(this).bind('change',selectForDelete);            
 });  

$(jQueryDomObj).bind(eventName,function) is very useful if you want to manipulate the element contents using javascript.

Tuesday, June 1, 2010

HibernateDaoSupport with HibernateTemplate - defaultAutoCommit set false...

I am working on a web application which needs hibernate for DB integration. So i decided to use hibernate with spring. As we all know that Spring is very lightweight and supports hibernate in an easy way. Also i am used to spring JdbcDaoSupport for DB integration and StoredProcedure class for SQL Server stored procedures.

While working this time i decided to use HibernateDaoSupport. Your DAO class must extend this class to use HibernateTemplate class.

Steps to make DAO using this,

- Extend HibernateDaoSupport and also an interface if you have.
- Define your methods which provides different Database operations (CREATE, DELETE, FETCH, UPDATE, INSERT etc...)
- Define required beans as below,

 <bean id="dataSource"  
 class="org.apache.commons.dbcp.BasicDataSource">  
  <property name="driverClassName">  
   <value>com.mysql.jdbc.Driver</value>  
  </property>  
  <property name="url">  
   <value>jdbc:mysql://localhost/testdb</value>  
  </property>  
  <property name="username" value="username" />  
  <property name="password" value="passwordforit" />  
  <property name="defaultAutoCommit" value="true" />  
  <property name="defaultTransactionIsolation" value="2" />  
  <property name="maxActive" value="100" />  
  <property name="maxIdle" value="50" />  
  <property name="minIdle" value="50" />  
  <property name="maxWait" value="100" />  
  <property name="initialSize" value="20" />  
 </bean>  
 <!-- Database Property -->  
 <bean id="hibernateProperties"  
 class="org.springframework.beans.factory.config.PropertiesFactoryBean">  
  <property name="properties">  
   <props>  
    <prop key="hibernate.hbm2ddl.auto">update</prop>  
    <prop key="hibernate.dialect">  
    org.hibernate.dialect.MySQLDialect</prop>  
    <prop key="hibernate.show_sql">true</prop>  
    <prop key="hibernate.cache.provider_class">  
    net.sf.ehcache.hibernate.EhCacheProvider</prop>  
   </props>  
  </property>  
 </bean>  
 <!-- Hibernate SessionFactory -->  
 <bean id="sessionFactory"  
 class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
  <property name="dataSource">  
   <ref local="dataSource" />  
  </property>  
  <property name="hibernateProperties">  
   <ref bean="hibernateProperties" />  
  </property>  
  <!-- OR mapping files. -->  
  <property name="mappingResources">  
   <list>  
    <value>myMapping.hbm.xml</value>  
   </list>  
  </property>  
 </bean>  
 <bean id="MyDAOTarget" class="com.dao.MyDAO">  
  <property name="sessionFactory">  
   <ref bean="sessionFactory" />  
  </property>  
 </bean>  

- Define transactionManager for transaction managment as below,

 <bean id="transactionManager"  
 class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  <property name="dataSource">  
   <ref bean="dataSource" />  
  </property>  
 </bean>  

- Define org.springframework.transaction.interceptor.TransactionProxyFactoryBean as below, which will eventually make proxy bean on the class given in target property.

 <bean id="MyDAO" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">   
   <property name="transactionManager">   
     <ref bean="transactionManager"/>  
   </property>   
   <property name="target">   
     <ref bean="MyDAOTarget"/>  
   </property>   
   <property name="transactionAttributes">  
     <props>   
       <prop key="insert*">PROPAGATION_REQUIRED, ISOLATION_READ_COMMITTED</prop>  
       <prop key="update*">PROPAGATION_REQUIRED, ISOLATION_READ_COMMITTED</prop>   
       <prop key="delete*">PROPAGATION_REQUIRED, ISOLATION_READ_COMMITTED</prop>  
       <prop key="find*">PROPAGATION_REQUIRED, ISOLATION_READ_COMMITTED, readOnly</prop>   
     </props>   
   </property>  
 </bean>  


- Use getHibernateTemplate().get(Class entityClass,Serializable id) OR getHibernateTemplate().load(Class entityClass,Serializable id) to load particular enoty from Database.
- Use getHibernateTemplate().find(String queryString,Object value) to find entities using HQL/SQL query.
- Use getHibernateTemplate().delete(), getHibernateTemplate().deleteAll() for removing entities from Database.
- Use getHibernateTemplate().update() OR getHibernateTemplate().saveOrUpdate() for updating/inserting entity in the Database.

It seems so easy right? But no, wait! All these works fine when you have <property name="defaultAutoCommit" value="true" /> . When you change this property to false, all updates to database will not take effect. Because in that case we need to begin and commit transaction form the code.

I have tried using getHibernateTemplate() for update operations but it failed. It doesn't work with transactions. So try as per the following method.

 public void updateMyObj(MyObj myObj) {  
   Session session = getSession(true);// true means allow create new session if required.  
   Transaction trans = session.beginTransaction();  
   session.saveOrUpdate(myObj);  
   trans.commit();  
 }  

Same thing works for any update operation. This is really strange, i tried for one whole day using getHibernateTemplate() but it never worked with <property name="defaultAutoCommit" value="false" />.

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.

Saturday, December 20, 2008

Telnet client with java...

Telnet is very important utiliy we use.We can call remote server commands and use different services running on perticular port.Mostly telnet server runs on 23,but can be differed .

Through java, if we want to make remote connection over some port then we have two different ways.

1. Use windows/linux telnet command line utility (which is same on both win and linux... :).)

OR

2. Use socket programming using java.net package.

In first way, we need to get hands on the process.We can achieve that using
Process p = Runtime.getRuntime().exec(<system command or exe path>)
But i don't think this should be used for telnet like communication,because telnet requires continuous session running on remote server and executing you commands.Sometimes it can be so that after executing several commands,you need to rollback so you can cancle all the commands.so its a continuous and sequential process most of the times.The Process class used can be out of our hands anytime if the executable crashes or if anything bad happen(Mostly..the exe crash...).


So, we have another,'Socket' way here, which connects to perticular host on given port number and try to open TCP connection with it.If the host is listening on port and connection accepted,then we can send our commands to the host.(I know, i know, that we all know sockets since our starting graduation days :) ,but let me tell guys... ).

There are two ways to make a telnet client using Sockets.
1.Make it CLI based,means which accepts every input from Command Line Interface entered by user.
2.Make it automated,which takes command list from some file or database,generates a script or list of commands and run it whole on host.

First one is quite easy,i think you all might have done that :).Just let me tell you little what to do...

1.CLI based Telnet...
Socket soc = new Socket(host,port);
DataInputStream din=new DataInputStream(soc.getInputStream());
PrintWriter dout = new PrintWriter(soc.getOutputStream(),true);

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
See,we have taken InputStream of socket and made a PrintWriter on the OutputStreamof it to send commands.Also we have taken BufferedReader for user inputs from CL.

...
....

do
{
char[] buffer = new char[8192];
int mark = bReader.read(buffer);
StringBuffer sb = null;
for(int i=0;i<buffer.length;i++){
char c = buffer[i];
if(c!='\0'){ //To avoid null characters printed...
if(sb == null){
sb = new StringBuffer(buffer.length);
}
sb.append(c);
}
}
System.out.print((sb!=null)?sb.toString():"-- No Response --");
Command=br.readLine(); //takes commands from CL by user...
if(!Command.equals("quit"))
{
dout.println(Command);
}
}while(!Command.equals("quit")); //exit the loop if user sends 'quit'...
...


This gives you same telnet as you got in your OS, so i think its simple but good to know :)


2.Automated Telnet...

It will be almost same,except we will have a ArrayList/Array of commands in hand before we create Socket.And then change the loop onto the list to execute all the commands one after another...

int j=-1;
String[] commands = new String[5];

...
....

do
{
j++;
char[] buffer = new char[8192];
int mark = bReader.read(buffer);
StringBuffer sb = null;
for(int i=0;i<buffer.length;i++){
char c = buffer[i];
if(c!='\0'){//To avoid null characters printed...
if(sb == null){
sb = new StringBuffer(buffer.length);
}
sb.append(c);
}
}
System.out.print((sb!=null)?sb.toString():"-- No Response --");
Command = commands[j];
if(Command==null || Command.length()<0)
break;
dout.println(Command+"\n");
}while(j<commands.length);
...

So this will executes all commands in commands Array of String.


So folks,this ends our telnet socket :).Same like this we can make client or scripts for FTP automation.It helps in real time situation when you need to make some jobs for backup,export/import files on remote host etc...Waiting for you responses...

Wednesday, December 17, 2008

Snmp4J - Java library for SNMP Communication...

We all know that if we need to use more on socket programming in java then we must use native code in c++.SNMP (Simple network Management Protocol) is used for communication with the network devices.Any network device can be queried using SNMP request.Snmp4j is the library which provides you implementation to make SNMP requests.

We can query any device (Switch,PC etc...) if it has a SNMP agent running,which will handle our SNMP request and respond with the proper data.This library made it so easy for us without looking into much details of SNMP.

In basic,SNMP is used for getting information (GET requests),but sometimes it can be used to set values in the device (SET requests).Assume that every device has a list of pre-defined variables in it,which are called OID(Object IDs).These OIDs will have a specific structure (which is called MIB file,which seems like a tree structured as in registry).

OID looks like 1.3.6.1.4.1.318.1.1.1.12.3.2.1.3.1, which has a special meaning.It has a description(name) and an associated value in it.When you query particular OID (i.e 1.3.6.1....),it will give its associated value.You can set its value also (if its allowed ;)).OIDs also have communities(Public,Private etc...) which shows permissions.Mostly public community is allowed to be viewed by SNMP requests.

See the example below how to make a SNMP request,
import org.snmp4j.*;

...
...

OctetString communityName = new OctetString("public");

String ipAddressUrl = strIpAddress+"/"+161; //161 is used for SNMP Agent...

Address targetAddress = new UdpAddress(ipAddressUrl);

TransportMapping transport = new DefaultUdpTransportMapping();

Snmp snmp = new Snmp(transport);

snmp.listen();

CommunityTarget target = new CommunityTarget();

target.setAddress(targetAddress);
target.setRetries(3);
target.setTimeout(500);

PDU pdu = new PDU();
pdu.setType(PDU.GET);

OID oid = new OID("1.3.6.1.2.1.1.");
VariableBinding vb = new VariableBinding(oid);

pdu.add(vb);
...
...

snmp.send(pdu, target);
So the last line, snmp.send(pdu, target), will return the SNMP4j Response having the value for OID we set in the PDU.This is just the example of how to get any data from OID.We can set the values using SET PDU.

Tuesday, November 25, 2008

Batch insert/update DB - Use XML as you data...

Today we have many strange requirements because of latest developments in the IT market. We are having tons of data to be inserted in databases or files etc.Mainly for DB operation, we can use batch insert/update, which calls DB for multiple rows of params.

This is not an excellent thing, but i think you should take care of this.Just think that if you are having 100 rows to be inserted in one table, and you make batch update call from you java code.How much time and resources it will take?We just can't answer this question.Yeah, we can't but we have different solution here.

Instead of making batch params data, you make and XML data using XSLT transformation or Castor mapping.We will see what these both things mean later. Today every Database server supports XML parameters as an input to Stored procedure/Function.You can pass your XML to the SP, and then handle the XML traversal logic inside the SP.You are done!

You just need to,

1.Create the XML data for Input param.
2.Pass the XML,execute the SP.
3.SP will handle the XML data and do the processing fetching the data from XML(Using Xpath traversal)
4.SP also can return resultset data as an XML content, which you can again transform map to Object.


XML Transformation: is done by javax.xml.Transform package, which takes one XML as input,Used XSLT file to transform input XML to XML format as defined by the XSLT.


Castor Mapping:is done by third party open source jar, which maps Object to XML and XML to object.So you can directly get XML/Object using this.

Monday, July 14, 2008

Remote Method call - EJB/HTTPClient/Web Service?

This is not a new thing i am talking about,but i have used this for first time. Until now i have been used to EJB for remote method invocations. I use it for some bussiness logic which is on another distributed server. And i am not ashamed of telling that i have not used Web services :(.

This was a need in my project to call a method of another application which can be on same machine or another. First i thought i need to call a EJB and its all mess because of heavy loads for a simple method call. But when i saw the implementation, i got confused how i will cuse it! But my senior told me to check using HTTPClient from apache commons.

Its very simple to call a method on servlet using HTTPClient. Check the code below. We will just use PostMethod class for parameters to be passed and execute the request. So as per the parameters,the servlet will do its work.
PostMethod postMethod = new PostMethod("http://some.blah.com");
postMethod.setParameter("some_id", "1");
postMethod.setParameter("param1", "any data");
postMethod.setParameter("param2", "any data");
...
int status = httpClient.executeMethod(postMethod); //status will be your response...
Its so simple. But though its not a call which returns something. I mean you cna see i am just passign some information to some method to invoke some processing which is independent and i don't need its response.

Tuesday, May 20, 2008

Controlling Module Dependencies in Eclipse

J2EE Module Dependencies is a critical issue in an enterprise application. You need your one web module to access some resources while prohibiting others. Similar is the case with EJB modules.

Let’s figure it out with Eclipse Web Tools Platform. I consider that you all have ability to create projects and modules in Eclipse; so skipping those steps. I have Eclipse 3.3 with WTP 2.0 M6.

I have created project with following details.

MyProject – Enterprise project

MyEJB_Module – Contains bean class

MyEJBClient_Module – Contains interfaces of EJB, VO, and BeanUtil.

MyWeb_Modules – Holds JSPs, servlets and all presentation tier stuffs.

MyJava_Module – Contains common classeslike constants, utilities.

Starting with MyProject, select properties from right click menu. In property dialog, select “J2EE Module Dependencies”. You will find all the modules. Select all as project is dependent on all modules.

Now you can configure dependency of individual module, let’s take an example of web module. In “J2EE Module Dependencies” window, you will find a radio button group which would has by default “Use EJB Client Jars” option selected. That radio button groups defines visibility of EJB jar.

As clients of any EJB should be isolated from bean classes, it is preferable not to select other options where you can define dependencies with EJB jar file. After all, EJB clients should not have any kind of dependencies with EJB jar.

Now here if I select MyEJB_ModuleClient.jar only, MyWeb_Module won’t able to access classes defined in MyJava_Module until you redefine module dependencies.

Similarity you can define dependencies with Utility project, specifically saying third party libraries. You want one module to access one jar and isolate others all you need to do is add library in main project (MyProject in my case) and then configure dependencies of other modules.

This feature takes care of dependencies on behalf of you and let you concentrate on other tasks.

Thursday, May 15, 2008

Servicemix PollingComponentSupport - stuck if lower period and higher threadPoolSize

Again i got one issue with servicemix Poller components.

We have two FilePoller components here and we kept the period to 10 minutes. Which means the instance of FilePoller will run at every 10 minutes. Now say if I have two instances, each run at 10 minutes, and 5 minutes gap between them. So it means after every five minutes, files will be picked by one of them. And the WorkManager, which is given to FilePoller as property, has threadPoolSize of 30.

All was working fine with this configuration.30 threads in pool, every five minutes any of two pullers will pick files. But now we have to change it. When we changed the period from 10 minutes to 1 minute, we got strange errors. Yes even you won't believe it. While testing concurrency we got, FileNotFound exception even though the file exists there, and many other concurrency issues. We looked into the logs and found that sometimes the load goes only on one server and the other is always idle doing nothing. Because when it comes, the first one is doing task.

Then we decided to decrease the thredPoolSize. Becasue if puller get 30 files for 30 threads from the pool, and when it comes to 31st file from the folder and if any of previous 30 threads is in the pool after it has completed its job, then it will take the file. It means, though we have pool size of 30, it may be possible that it can process more than 30 files per instance (say 32 to 38 files). So we decided to make pool size to 10.

Now after making 10 it seems to be working fine. Each one is picking almost equal numbers of files and sharing load as it should. Let’s see if more issues are coming or not.

So, key thing to be remembered is
"Keep you threadPoolSize and period on which instance will run in proportion to each other. If period is long then threads can be more but if you want to reduce the period, you must take care of pool size."

Tuesday, May 13, 2008

Java optimization and performance

No new Exception if not needed

Many of us do this when we want to throw an error. But if you are throwing exception from another catch, then don't make new exception object. Keep throwing the same exception which you caught if possible. This will be better for performance. And also in new exception usually we change the description only to reflect the perfect error cause, but other ways are there to track it.

Avoid excessive synchronization

Yah threading can be a bit complex situation sometimes in java. And we all use synchronization to avoid dead locks. But it needs a more attention then we give it. Try to make a block of code synchronized rather then making the whole method synched. The whole method will stop all other threads, waiting to go inside it. It will generate more overhead. So keep the design like we need less sync code.

Release DB and File IO

This is the most case in which we all do something wrong.
DB connections must be closed after completing your DB transactions because its a limited resource.

Also if you are using File IO, then must close file streams after completing the task.

Best way for this is, to write the releasing code in 'finally' block of the method.

Use StringBuffer/StringBuilder rather than String

We use string manipulations in our daily coding many times. And all we do is always making new String object. As most of us know, String is immutable object (which means once assigned you can't change its value), so when you assign existing String object another value, it will make new String object. And most string operation generates lot of small String objects.

If it’s possible to use StringBuffer or StringBuilder instead of String then its more more way better. Because it will be one object having all your data in it and you can get String form it when you want.

Now StringBuilder is nonSynchronized and StringBuffer is synchronized. So if you don't have threading issues and don't need Sync, then you must use StringBuilder which is included since jdk 1.5.

Later on we will talk about more points also when i remember them :)

Friday, May 9, 2008

servicemix problems: NormalizedMessage getContent,copyPropertiesAndAttachments()

Though servicemix is widely used and very nice ESB framework, it has some basic problems.The one i am talking about here is very little thing but it can be annoying if you forget this or don't know this.

While creating and sending NormalizedMessage object from any data, after doing that if you read data using NormalizedMessage.getContent() method and send the message object with exhchange to deliveryChannel, using DeliveryChannelImpl.send(MessageExchange) method, then you will get null exception in DeliveryChannelImpl class.

Yes this is true.I don't know why, but it removes content from the message object.Only the content is removed and the properties are still there.

You can read properties from it in same component as many times as you want.If you are forwarding same message to next component, properties will automatically goes.But if you read content once, you must set it again :(.

Also remember that if you need to make new MessageExchange, then you must copy all properties and attachments using TransformComponentSupport.copyPropertiesAndAttachments(outExchange,inMsg,outMsg) method.Then all your data from one message will be copied to another message.

So keep checking this if you getting null Exceptions while sending message through DeliveryChannel.

Spring Framework problem : SqlReturnResultSet() not returned

One more problem with servicemix and spring is in DAO classes, when you make any private static class of StoreProcedure, then in its constructor you must declare SqlReturnResultSet before you declare SqlParameter.Otherwise you will not be able to find return data from StoredProcedure execution.Check the code below,
public MySp(JdbcTemplate jdbcTemplate){
super(jdbcTemplate,"sp_mysp");
declareParameter(new SqlReturnResultSet("strRs",rsMyResultSet));
declareParameter(new SqlReturnResultSet("strRs1",rsMyResultSet1));
declareParameter(new SqlParameter("myId", Types.INTEGER));
compile();
}
so keep in mind while using Spring DAO support.Must declare resultsets first.


Thursday, May 1, 2008

Using Struts tags - <logic:iterate>,<logic:equal>,<bean:write>

I was wondering what should i write about now.And suddenly i got this to do.
I have a small change in the jsp which is made using struts framework.In struts, there are many tags which are easy to use and generate output fast.easy to write.

In struts, we have ActionServlet,Action classes and ActionForms.

ActionServlet will transfer the request to ActionServlet with ActionForms containing all the HTML form data.so you can access any data of the of ActionForm from Servlet request.

See the below code.then we will talk regarding it.

<select name="sel1" id="selTestStruts" style="width:90px;">
<option value="0" selected="selected">Please Select
<logic:iterate id="myBean" name="someForm" property="someFormProp1">
<logic:equal value="test" property="someStrPropOfMyBean" name="myBean">
<option value='<bean:write name="myBean" property="someStrPropOfMyBean"/>'><bean:write name="myBean" property="someNamePropOfMyBean"/></option>
</logic:equal>
</logic:iterate>
</select>


here we are trying to fill HTML select box using struts' <logic:iterate>, <logic:equal><bean:write> tags.

<logic:iterate> will iterate on 'someFormProp1' of 'someForm' which is in the http request.it will make 'myBean' from property 'someFormProp1' which is a List of some data.

You can simply write any property from that 'myBean' we made above.But i also shown here how you can put logic to seperate things on some property value so you don't need to put logic in the SP or generate another property for it.

<logic:equal> checks the value of property named 'someStrPropOfMyBean' with the string given in 'value="test"' attribute (means with 'test' here). If the value matches then only it will make new <option> for <select> box.

same thing you can do with not including some specific value match using <logic:notEqual>

<bean:write> tag will simply write property 'someStrPropOfMyBean' of 'myBean' which is a object of some Value Object class from the List property 'someFormProp1' of 'someForm'.

Though this is very simple thing but i write because may be this can be helpful to some newbies.