Purpose of ContextLoaderListener – Spring MVC

When we are working with Spring MVC and are also using Spring in the services layer, we provide two application-contexts. The first one is configured using ContextLoaderListener and the other with DispatcherServlet. A sample configuration in web.xml is mentioned below:

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>    
        /WEB-INF/config/applicationContext-service.xml
        /WEB-INF/config/applicationContext-dao.xml
    </param-value>
</context-param>
<servlet>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/config/servlet-context.xml
           ***/WEB-INF/config/applicationContext.xml***
        </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

After reading the Spring documentation, following is the understanding:

a) Application-Contexts are hierarchial and so are WebApplicationContexts. Refer documentation here.

b) ContextLoaderListener creates a root web-application-context for the web-application and puts it in the ServletContext. This context can be used to load and unload the spring-managed beans ir-respective of what technology is being used in the controller layer(Struts or Spring MVC).

c) DispatcherServlet creates its own WebApplicationContext and the handlers/controllers/view-resolvers are managed by this context.

d) When ContextLoaderListener is used in tandem with DispatcherServlet, a root web-application-context is created first as said earlier and a child-context is also created by DispatcherSerlvet and is attached to the root application-context. Refer documentation here.

Refer to the diagram below from the Spring documentation.

Advertisements

Reverse the order of a Sentence in Java

Recently, in an interview, i was asked to reverse a sentence, i.e. given a String “THIS IS AN INTERVIEW” , reverse it to “INTERVIEW AN IS THIS” without using any advanced APIs of Java.

I had tried to solve the problem with the java.util.regex.Pattern class after realizing that usage of StringTokenizer is discouraged in the Java Docs. However,the solution was not accepted as it used Pattern class. So, i was determined to solve the problem myself and have come up with the below solution. Please provide your valuable feedback. The soultion here uses basic classes like String, StringBuilder and char. The solution here can be enhanced for a character-sequence. Currently, it works only for a single character.

import java.util.regex.Pattern;

public class TestStringSplitAndReversal {

    public static void main(String args[]) {
        String testString = "THIS IS A TEST";
        char regex = ' ';
        String[] reversedString = TestStringSplitAndReversal.split(regex, testString);
        int size = reversedString.length;
        //For String reversal
        for (int i = size - 1; i >= 0; i--) {
            if (reversedString[i] != null)
                System.out.println("Element:::" + reversedString[i]);
        }
    }

    // Regular Splitting using Java's API
    public static String[] split(String regex, String str) {
        return Pattern.compile(regex).split(str);
    }

    // Splitting without using any advanced APIs of Java
    public static String[] split(char regex, String str) {
        char[] actual = str.toCharArray();
        // char[] temp=new char[str.length()];
        StringBuilder tempStr = new StringBuilder();
        int j = 0, k = 0;
        String[] result = new String[str.length()];
        int resultSize = 1;
        for (int i = 0; i < actual.length; i++) {
            // temp[j++]=actual[i];
            tempStr = tempStr.append(actual[i]);
            if (regex == actual[i]) {
                result[k++] = new String(tempStr);
                // j=0;
                resultSize++;
                // temp=new char[str.length()];
                tempStr = new StringBuilder();
            }
        }
        // result[k++]=new String(temp);
        result[k++] = new String(tempStr);
        return resizeArray(result, resultSize);
    }

    //This resizing is required as once an Array is initialized to a size, 
    //it cannot be shrinked.Hence, we need to create a new Array.
    public static String[] resizeArray(String[] original, int resultCount) {
        String[] result = new String[resultCount];
        for (int i = 0; i < original.length; i++) {
            if (original[i] != null) {
                result[i] = original[i];
            }
        }
        return result;
    }

}

Dynamically Changing JBoss Ports

Changing Http Port:

Add the required http port to ${jboss}/server/default/deploy/jbossweb.sar/server.xml in the the following element:

Changing JNDI and RMI Port:

  • Add the correct port to your ${jboss}/server/default/conf/jndi.properties (see above). The entry might look like java.naming.provider.url=jnp://myhost:1199.
  • Change the settings in ${jboss}/server/default/conf/jboss-service.xml: Find the entry for mbean code=”org.jboss.naming.NamingService” and change the attributes Port and RmiPort to the appropriate.

Dynamically Changing the Http/JNDI/RMI Port:

When two JBoss servers are running on one physical machine, you can dynamically change the Http/JNDI/RMI Ports by executing the following command during server start-up in JBoss bin folder:

nohup ./run.sh -c SERVER_NAME -b 0.0.0.0 -Djboss.service.binding.set=ports-02 -Dconfiguration.url=CONFIG_FOLDER

The above command increments the port numbers by +200 i.e. 8080 becomes 8280 , 1099 becomes 1299, etc

SERVER_NAME=myserver
CONFIG_FOLDER=file:///home/user/softwares/jboss/server/myserver/conf/my-config

nohup generates the nohup.out file in the same jboss bin folder where we need to execute the above command

Note: Default JBoss Http port=8080, JNDI port=1099, RMI port=1098, AJP port=8009

Courtesy: JFire

Escape ‘_’ in SQL and Java

We had a table for which, a column say ‘ENAME’, was allowed to have underscore(_). The same column was allowed to be searchable from Flex User-Interface. As underscore(_) was allowed to be used in the text-box, we ended up retrieving all the records from the table when the user entered only ‘_’ in the text-box and queried for results. This happens as underscore(_) has a special meaning in Oracle and is used as a wild-card character(for single character) in SQL parlance.

The solution to this problem was to escape the underscore(_) in SQL and treat it as just another character as opposed to a wild-card character and escape it in Oracle SQL. Following should be the SQL query:

SELECT * FROM EMPLOYEE WHERE ENAME like '%\\_%'  ESCAPE '\';

The same fix applies to even ‘%’ which is used as a wild-card character for multiple characters.

In Java, we had to do the following as we were appending the search-value as a query parameter in SQL.

String query="SELECT * FROM EMPLOYEE";

if(!"".equals(ename))
{
    query=query.concat(" WHERE ENAME like "+"'%"+ename.replaceAll("_", "\\\\_")+"%'  ESCAPE '\\' ");

}

Just apply the above fix and fail the QA from breaking our robust Java and Oracle code.

Serialization in Java – 1

Serialization in java is a topic in it-self. More often then not, we are caught unaware of a few serialization principles. Here, we try to cover two important aspects in the context of inheritance.
a. Super-class is Serializable. How to ensure that a Child-class shouldn’t be Serializable?
Solution:Add default private methods of readObject() and writeObject() in the Child-class and throw a NotSerializableException.

class SuperClass implements Serializable{
     private String state;

     public SuperClass(String state){
         this.state=state;
     }

     public String getState(){
         return state;
     }
     public String setState(String state){
         this.state=state;
     }
}

class ChildClass extends SuperClass{

    private void writeObject(ObjectOutputStream out) throws IOException{
          throw new NotSerializableException("Dont serialize me!");
    }
    private void readObject(ObjectInputStream in) throws IOException{
          throw new NotSerializableException("Dont serialize me!");
    }

}

b. Super-class is not Serializable. How to ensure that a Child-class should be Serializable?
Solution: Provide a no-arg constructor in the Super-class and make it accessible to the child-class.

class SuperClass  {
     private String state;

     public SuperClass(){
     }

     public SuperClass(String state){
         this.state=state;
     }

     public String getState(){
         return state;
     }
     public String setState(String state){
         this.state=state;
     }

}

class ChildClass extemds SuperClass implements java.io.Serializable{

}

Courtesy:

Todd Greanier’s article
John Zukowski’s article
StackOverFlow

For a quick read on Serialization, refer this article.

SQL Query For Pagination on Database Side

Recently, i was tasked with implementing pagination for a data-grid in my application on the server-side. The pagination which i choose, is enabled at the database end by using SQL. After a bit of google reasearch, i stumbled upon the following query which seems to fit the bill.

select * 
  from ( select /*+ FIRST_ROWS(n) */ 
  a.*, ROWNUM rnum 
      from ( your_query_goes_here, 
      with order by ) a 
      where ROWNUM <= 
      :MAX_ROW_TO_FETCH ) 
where rnum  >= :MIN_ROW_TO_FETCH;

where
FIRST_ROWS(N) tells the optimizer, “Hey, I’m interested in getting the first rows, and I’ll get N of them as fast as possible.”
:MAX_ROW_TO_FETCH is set to the last row of the result set to fetch—if you wanted rows 50 to 60 of the result set, you would set this to 60.
:MIN_ROW_TO_FETCH is set to the first row of the result set to fetch, so to get rows 50 to 60, you would set this to 50.
Courtesy : Ask Tom, Q & A

Check Java Class Version

There is always a situation in a java developers life, when he needs to deal with various versions of java and incompatibilites which might arise with them.In my regular googling exercise, i found a very good solution given by Real Gagnon.So, to identify the version of java class file, is to extract the class file from the jar/war and just run the below program:

import java.io.*;

public class ClassVersionChecker {
    public static void main(String[] args) throws IOException {
        for (int i = 0; i < args.length; i++)
            checkClassVersion(args[i]);
    }

    private static void checkClassVersion(String filename)
        throws IOException
    {
        DataInputStream in = new DataInputStream
         (new FileInputStream(filename));

        int magic = in.readInt();
        if(magic != 0xcafebabe) {
          System.out.println(filename + " is not a valid class!");;
        }
        int minor = in.readUnsignedShort();
        int major = in.readUnsignedShort();
        System.out.println(filename + ": " + major + " . " + minor);
        in.close();
    }
}

> java ClassVersionChecker ClassVersionChecker.class
ClassVersionChecker.class: 49 . 0

Comparison Chart:

major  minor Java platform version 
45       3           1.0
45       3           1.1
46       0           1.2
47       0           1.3
48       0           1.4
49       0           1.5
50       0           1.6

Courtesy: Real Gagnon(Click Here for actual post)