Tuesday, December 29, 2009

Get Client IP in Axis2

If you are using Axis2 for developing your web services, then in most cases you would want to obtain the client's IP address.

The following method gives you that.

//Import statement to import MessageContext class
import org.apache.axis2.context.MessageContext;

/*
* This method gets the client IP address using axis2 MessageContext
*
* @return Client IP : String
*/
private String getClientIP () {

      return (String)(MessageContext.getCurrentMessageContext()).getProperty(MessageContext.REMOTE_ADDR);

}

Thursday, December 24, 2009

Log4j setup

This is a small help section on setting up log4j in your application and making use of it.
Log4j ofcourse has lot of benefits and is advisable to use to keep tract of the activities in your application.

Following are a few steps to configure log4j

1. Download the jar file from http://logging.apache.org/log4j/1.2/download.html
2. Put the jar file in the folder where you put your libraries (lib folder)
3. Now we need to create a configuration file which can be either a .xml file or a .properties file.
I prefer .properties file as it is easy to create and configure.


I will not go deep into it, as for such things you will find many articles.
I have put a sample .properties file which you can use in you application, just a few changes ofcourse.

log4j.rootCategory=INFO, CONSOLE
# AppFileAppender- used to log messages in the application.log file.
log4j.appender.AppFileAppender=org.apache.log4j.FileAppender
log4j.appender.AppFileAppender.File=../logs/application.log
log4j.appender.AppFileAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.AppFileAppender.layout.ConversionPattern= %-4r [%t] %-5p %c %x - %m%n

log4j.logger.com.mycompany.myapp=DEBUG,AppFileAppender

The above is goof enough for your application.
(i) The first line is generic, so just paste it.
(ii) Next is the comment, and after that a file appender is defined. Its a log4j thing, so just copy-paste it.
(iii) The next is the log file. By default the log file is created in the config folder of your server. You can change it by specifying the relative path.
(iv) Next 2 lines are regarding patterns, so just copy-paste.
(v) The last line is to link a package to a FileAppender. You can have different files for having logs of different packages. (log4j.logger. is log4j thing, com.mycompany.myapp is the package)

Thats it, you are ready to use log4j in your application. The changes would be in the log file name and the package name.

Now in your classes, make sure you import org.apache.log4j.Logger;
Then create a logger as follows
static Logger logger = Logger.getLogger(WorkerClass.class);

Define this logger immediately after the class and don't keep it in any methods, so its accessible for the entire class.

Then all you do is
logger.info("This is the message to put in the log");
You can use various methods (levels) like debug(), info(), warn(), error(), fatal() etc.
You get more info on these in
http://logging.apache.org/log4j/1.2/manual.html

I guess that was easy. And if it was, then start using log4j and avoid System.out.println in you application. Do it from the start of the application and avoid having to make changes later.

This ofcourse is a very basic of log4j, once you learn more from the link I have given above, you can do lot more things with log4j

Monday, December 21, 2009

Java Collections : Which one to use

When I initially started using Java and to be frank, until quite recently, I was never sure whether I am using the right collection for in my code.
Initially though, I never bothered about it and was using anyone which suites my needs (eg: Vector to store list of values and HashMap to store key value pair). I rarely used other implementations, unless my senior asked me to use it.

But later I did realise that using the right implementation for the right piece of work is important and can improve your code and the overall performance of your application.

I have put down a segment here for java developers who are having trouble making the decision on the right collection. to make it simpler for a java developer, I have put it in our language syntax, with if / else loop (The one we use most when we are starting up)

//Choose the collection
if ("Need to store key value pair")
{
  Use Map;
   //To choose the implementation
   if ("Map must be sorted by keys" && "Dont need to store null key")
   {
     Use TreeMap; //If speed is a major criteria, then you better use HashMap and sort it by your self.
   }
   else if ("Map must be fully synchronised" && "Must not allow null key and values")
   {
     Use HashTable;
   }
   else if ("Map must be thread safe while insertion" && "Must allow null key and values")
   {
     Use ConcurrentHashMap;
   }
   else if ("Map need not be thread safe" && "Must allow null key and values" && "Needs to be fast")
   {
     Use HashMap;
   }
   else if ("Need to store multiple values per key")
   {
     Use MultiMap;
   }
   else if ("Map must be fully synchronised" && "Must not allow null key and values" && "The order of insertion must be maintained")
   {
     Use LinkedHashMap;
   }
}
else if ("Must not store duplicates" && "Order of elements stored does not matter") //also, dont need key value pair, but have to store single values
{
   Use Set;
   //To choose the implementation
   if ("Set needs to be sorted")
   {
     Use TreeSet; //If speed is a major criteria, then you better use HashSet and sort it by your self.
   }
   else if ("Set need not be sorted" && "Speed is important")
   {
     Use HashSet;
   }
}
else if ("Will need to store duplicates" || "Order of elements stored matters" || "Need to have control over where the element is added")
{
   Use List;
   //To choose the implementation
   if ("Need to add and remove more frequently" || "Need the functionality of a Queue/Stack/Double-ended Queue")
   {
     Use LinkedList;
   }
   else if ("List must be synchronized")
   {
     Use Vector;
   }
   else if ("List need not be synchronized" && "Speed is important")
   {
     Use ArrayList;
   }
}
else if ("Amount of data is predictable" && "Amount of data is less")
{
   Use Array; //If searching is more important, use ordered array, else if insertion speed is important, use unordered array
}

There are ofcourse a lot more implementations of the collections. But I have tried to put in a few which are frequently used by us. And I believe, most of the operations can be handled by those mentioned above.

To know more about each implementation or collection, you can go through the Java API.

Please note that the above is based on my knowledge and if you see any mistakes, I am ready to correct myself.

Read and Write objects to request and response

Here is a simple code sample to read/write an object to the HttpServletRequest/Response

/*
* Read an object from the input stream.
*/
private Object readObjectFromRequest ( HttpServletRequest req ) throws IOException {

ObjectInputStream oos = null;
try {
oos = new ObjectInputStream(req.getInputStream());

return oos.readObject();
} catch (ClassNotFoundException ex) {
throw new IOException("Accessing the object threw a ClassNotFoundException : "+ex);
} finally {
if (oos != null) oos.close();
}
}

/*
* Writes an object into the output stream.
*/
private void writeObjectToResponse ( HttpServletResponse resp, Object o ) throws IOException {

ObjectOutputStream oos = new ObjectOutputStream(resp.getOutputStream());
//Write the object into the response output stream and close the stream.
oos.writeObject(o);
oos.close();
}

GlassFish vs Tomcat

At first, I must tell you that Glassfish and Tomcat is not to be compared as one is a App server and other is a simple web server. But since most of the people seem to ask the question, I have put down a few words here which may be helpful.

Tomcat is a decent enough web server for the smaller scale applications.
Glassfish, JBoss, Websphere, etc. are heavy weight application servers that support the EJB standard and many more advanced features out of the box.
If you want to use Enterprise Javabeans in your application then Glassfish or similar application servers are the way to go; if you only want to develop using servlets & JSPs or possibly a POJO based framework like Spring, Tomcat may be more than enough.

Then again, if you are writing a critical business application for which for example security is a big deal, you may want to start thinking about an application server again.
It all depends on the requirements.

Tomcat is part of Glassfish :
Glassfish uses a derivative of Apache Tomcat as the servlet container for serving Web content.

Below are the advantages of App server like GlassFish over Web server like Tomcat
  • Data and code integrity
    By centralizing business logic on an individual server or on a small number of server machines, updates and upgrades to the application for all users can be guaranteed. There is no risk of old versions of the application accessing or manipulating data in an older, incompatible manner.

  • Centralized configuration
    Changes to the application configuration, such as a move of database server, or system settings, can take place centrally.

  • Security
    A central point through which service-providers can manage access to data and portions of the application itself counts as a security benefit, devolving responsibility for authentication away from the potentially insecure client layer without exposing the database layer.

  • Performance
    By limiting the network traffic to performance-tier traffic the client-server model improves the performance of large applications in heavy usage environments.

  • Total Cost of Ownership (TCO)
    In combination, the benefits above may result in cost savings to an organization developing enterprise applications. In practice, however, the technical challenges of writing software that conforms to that paradigm, combined with the need for software distribution to distribute client code, somewhat negate these benefits.

  • Transaction Support
    A transaction represents a unit of activity in which many updates to resources (on the same or distributed data sources) can be made atomic (as an indivisible unit of work). End-users can benefit from a system-wide standard behaviour, from reduced time to develop, and from reduced costs. As the server does a lot of the tedious code-generation, developers can focus on business logic.


Conclusion
Given the above benifits, we need to find out whether we are actually using these features. If not, then the app server is nothing but a burden. If you think you may use these features in the future, then we better use the app server in the future itself. Since the point which needs to be noted is that Glassfish actually uses Tomcat for serving web content.

If you think we need few of the goodies which come with app server like security, performance, transaction support, centralised configuration. We need to find out if we are actually using those and if yes, then we have to stay with Glassfish. If not, how can we implement them and take advantage of using a application server like GlassFish.

Enterprise Service Bus (ESB) : To use or not to use

We no longer bring services together within a program but we bring them together in an environment which no longer needs programming. This environment is an ESB, an Enterprise Service Bus. Services are grouped together through an orchestrate/choreographic function. This gives us very dynamic, simple and viewable application constructions.

One of the main strengths of an ESB is processing messages. Message in, message out, perhaps with protocol or format mediations applied. When the requirements clearly call for message processing, an ESB is going to have several advantages, including the ability to handle greater complexity in the transformations. If the requirements call for one of the basic ESB functions, such as message routing, transformation or protocol mediation, an ESB would be the clear choice.

Another strength of an ESB is performance. An ESB is designed to be able to handle large volumes of messages. If, for example, the requirements say that there will be 200,000 messages per day, the ESB would clearly be the better choice.

If the requirements are data-centric, an ESB is the clear choice.

ESB is well suited to scenarios where loose coupling, scalability and robustness are required.

A checklist to judge whether your application needs ESB


  • Are you integrating 3 or more applications/services? If you only need to communicate between 2 applications, using point-to-point integration is going to be easier.


  • Will you really need to plug in more applications in the future?


  • Do you need to use more than one type of communication protocol? One Http, another is JMS etc.


  • Do you need message routing capabilities such as forking and aggregating message flows, or content-based routing? This is true if you have multiple versions of the service and you need to forward the request to a service based on the content in the request.


  • Do you need to publish services for consumption by other applications?


  • Do you have more than 10 applications to integrate?


  • Do you really need the scalability of an ESB? It’s very easy to over-architect scalability requirements of an application. ESB scales down as well as up making it a popular choice for ‘building in’ scalability. However, there is a price to be paid for this since you are adding a new technology to the architecture.


  • Do you need to use the security features provided in ESB. ESB provides Inbound and outbound security which can be handled at various levels. We have transport level, authentication, authorization built into ESB implementations.


  • Do you wbant to manage software load alancing within ESB.


If the above points do not satisfy, then we better not go with ESB as in that case ESB will be nothing more than a pain.

But if you think your application satisfies all the above points then ESB is a advantage. Also, ESB does not have performance issues and will be better than the delegator that most of us implement.

Please see below few reference to ESB

What is ESB : http://en.wikipedia.org/wiki/Enterprise_service_bus

Open source ESB for Java : http://java-source.net/open-source/enterprise-service-bus

Oracle service bus (best in the industry) : http://www.oracle.com/appserver/esb.html

Whether to use ESB or not : http://rossmason.blogspot.com/2009/07/to-esb-or-not-to-esb.html

Saturday, March 14, 2009

Last Day of the month - Java

Playing with dates is always fun.

Here is one of those....

//Given the month, will return the date of the last day of the month
//parameter is month number (starting from 0)
public static Date getLastDayOfMonth (int month) {

Calendar calendar = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat( format );

Date d = new Date();
d.setMonth( month );

calendar.set(Calendar.MONTH, month);
//System.out.println("Value "+ calendar.get(calendar.MONTH));
int lastDateofMonth = calendar.getActualMaximum(Calendar.DATE);
d.setDate( lastDateofMonth );

return d;
}

Quick Sort - Java Vector

Here is a small code snippet to sort a 2D Vector in Java.

//pos is the column number to be sorted with
private void quickSortVector(Vector v, int start, int end, int pos)
{
int i = start; // index of left-to-right scan
int k = end; // index of right-to-left scan

if (end - start >= 1) // check that there are at least two elements to sort
{
String pivot = (String)((Vector)v.elementAt(start)).get(pos); // set the pivot as the first element in the partition

try {
while (k > i) // while the scan indices from left and right have not met,
{
while (((String)((Vector)v.elementAt(i)).get(pos)).compareToIgnoreCase(pivot) <= 0 && i <= end && k > i) // from the left, look for the first
i++; // element greater than the pivot
while (((String)((Vector)v.elementAt(k)).get(pos)).compareToIgnoreCase(pivot) > 0 && k >= start && k >= i) // from the right, look for the first
k--; // element not greater than the pivot
if (k > i) // if the left seekindex is still smaller than
swapVector(v, i, k); // the right index, swap the corresponding elements
}
swapVector(v, start, k); // after the indices have crossed, swap the last element in
// the left partition with the pivot
quickSortVector(v, start, k - 1, pos); // quicksort the left partition
quickSortVector(v, k + 1, end, pos); // quicksort the right partition
}
catch (ArrayIndexOutOfBoundsException ae) {
System.out.println("Could not sort vector : Array out of bound exception for column "+ pos);
return;
}
catch (Exception e) {
System.out.println("Could not sort vector : Exception "+ e);
return;
}
}
else // if there is only one element in the partition, do not do any sorting
{
return; // the array is sorted, so exit
}
}

Catch JS errors on web page or web applications

Here is a code snippet to catch the script errors which could be generated on your web application.

It should be such that when its development environment, it must show a alert message and when its production environment, it sends a email or logs into a table.

//
// Traps all js errors
function catchJSError(a,b,c,d) {
//var lines= document.body.innerHTML.split('\n');
//var errorline = lines[c];


// Get error line
var source = document.body.innerHTML;
source = source.split("\n");

var bugline = ((c-1) + ":" + source[c-1] + "\n" +
(c) + ":" + source[c] + "\n" +
(c+1) + ":" + source[c+1] + "\n"
);



var bug = "<b>JS Error:</b> " + a +
"<BR><b>Error in the file:</b> " + b +
"<BR><b>On Line:</b> " + c +
"<BR><b>Character:</b> " + (isIE==true)?event.errorCharacter:"0" +
"<BR><b>Window Title:</b> " + document.title +
"<BR><b>Error Type:</b> " + (isIE==true)?e.errorCode:"0" + "<BR><BR>";


var file = window.location.pathname;
file = file.substring (file.lastIndexOf("/"));

var subject = escape("JS error on " + window.location.host + " : " + file);

var live_servers = "prod.checkingserver.com";

// Send email if a live server
if (live_servers.indexOf(document.domain)>=0) {

sendAjaxRequest("reportJSError.do", "subject="+subject+"&bug="+ escape(bug) );
}
else
alert(bug.replace(/<b>/g,"").replace(/<\/B>/g,"").replace(/<BR>/g,"\\n"));


return false;
}
window.onerror=catchJSError;

New blog from me

Hey guys

I have created this new blog to share my small knowledge on software development techniques and the related topics.

I just hope that this helps some of you atleast.