Friday, December 16, 2011

Difference between ServletConfig and ServletContext

Following table lists down the main differences and others things are discussed afterwords:
ServletConfigServletContext(It should have been ApplicationContext)
One ServletConfig object is created per servlet One ServletContext object is created per Application
Can be used to pass deployment time information to the Servlet. Information is stored as parameters in the deployment descriptor(web.xml) Can be used to share Application level information across servlets and is this information is also stored in the web.xml as well as parameters (So it kind of acts as GlobalContext or Application Context)
Provides a set of methods to set and get the initialization configuration information Provides a set of methods to the servlet so that servlet can communicate with the Container
------------------------Servlet can access a ServletContext object only through ServletConfig object

Working with ServletConfig:

We will explaing here how to declare the Servlet init Parameters in in the Deployment Descriptor(web.xml) and how to retrieve them in the servlet also how to get the object of Servlet Context from ServletConfig.
web.xml: Declaring init parameters for a specific servlet

    
    SampleServ
    SampleServ
    in.javaespresso.web.SampleServ
    
     Sample Init Parameters
     servParamservValue
  
Servlet Code: Getting init parameters inside the servlet
getServletConfig().getInitParameter("servParam");
Servlet Code: Getting ServletContext object using ServletConfig
ServletContext context = getServletConfig().getServletContext();

Working with ServletContext:

Let us get the context paramteres declared in the web.xml in the servlet and jsp
web.xml: Declaring context parameters

    Sample context parameters
    emailjava.espresso@gmail.com
Servlet Code: Accessing context params in Servlet
getServletContext().getInitParameter("email")
JSP code: Accessing context params in JSP
<%
getServletContext().getInitParameter("email");
%>

Please find the code for the article attached here

Monday, November 14, 2011

Remote Method Invocation(RMI) Example

Here, we will learn basics of RMI and will implement a small example

Remote Method Invocation Basics
As the name suggests,it is a system to call remote method,which may be on other JVM or other computer. It is built on top of Sockets. But,you don't have to deal with sockets and protocols directly. You can directly call a method on some other machine and it works,as if you have called it locally. To achieve this it passes the objects over the network(objects should be Serializable).

Drawback: RMI can only be used in java. Interaction with other language platform is not possible.

Requirements of RMI
Client Requirement
Let us suppose there is a server Object which is registered.
* Client Object have to find the Server Object(by looking it up in registry)
* Serialize the parameters and send
* Deserialize the response from the server

Server Requirement
* Server should be a remote object
* The remote object should be registered(rmiregistry is used for registration)

Example

HelloInterface.java
import java.rmi.Remote;
import java.rmi.RemoteException;

public interface HelloInterface extends Remote {
 public String sayHello() throws RemoteException;
 }

Hello.java
import java.rmi.RemoteException;
public class Hello implements HelloInterface 
{

private String message; 
public Hello (String msg) throws RemoteException {
message = msg;
 }
public String sayHello() throws RemoteException {
 return message;  
 }
}
HelloServer.java
import java.net.MalformedURLException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

class HelloServer {

 public static void main(String[] argv)  throws RemoteException, MalformedURLException {
  
  try{
   Hello remoteObj=new Hello("This is test RMI");
    Remote obj = UnicastRemoteObject.exportObject(remoteObj, 9502);
          Registry r = LocateRegistry.createRegistry(9502);
          r.bind("RemoteHelloServer", obj);
   System.out.println("Hello Server is ready.");
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
  
 }
}

Steps for compilation:
1)javac HelloInterface.java
2)javac Hello.java
3)javac HelloWorld.java
4)rmiregistry //In a separate command prompt
5)rmic -vcompat Hello //will generate Hello_Stub.class and Hello_Skel.class
6)java HelloWorld

After step 6,Server is up

Steps for client code:
* Copy the HelloInterface.java and Hello_Stub.class file in client area
* Write a client program HelloClient.java, which looks up in registry.

HelloClient.java
import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

class HelloClient {
 public static void main(String[] args) {
  try {
   Registry registry;
  HelloInterface hello;
  registry=LocateRegistry.getRegistry(
                "localhost",(new Integer(9502)).intValue());
  String name = "RemoteHelloServer";
  
   hello = (HelloInterface) registry.lookup(name);
   System.out.println(hello.say());
  } catch (Exception e) {
   System.out.println("HelloClient exception: " + e);
  }
 }
}

Compile and run the client code.
After this it is easy to expose your methods with RMI.

Monday, October 31, 2011

Base64 encoding and decoding in Java

What is Base 64 Encoding Scheme?
Wiki says -
"Base64 is a group of similar encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The Base64 term originates from a specific MIME content transfer encoding."

In simple terms Base64 encoding is a Binary to ASCII text conversion technique. Other such techniques available are quoted-printable, hexadecimal, BinHex, etc.

Binary to text encoding/decoding techniques are used when there is doubt that the transmission protocol/channel might not be capable of handling the non-textual data, best examples are email sent via MIME, Usenet. For example, many browser normally convert a space in URLs to %20D or such like characters and you might be in trouble if your server doesn't reconvert them but you can't possible crack down every such possible case. So better is use an encoding scheme that converts your data to text based characters.

your data => [ Base64 Encoding System ] => Textual Data
Image      => [ Base64 Encoding System ] => Image converted to text data

Is Base64 Encoding scheme a Encryption technique? NO, don't even think like an idiot. it is simply converting data from one form to another so that no modification happens due to the limitation in my transmission protocol/channel but there is not concept of cryptography involved at all.

How Base64Encoding works? Well, look at Wiki example, it is pretty much straight forward and clear.
Same example is given below as well..
Text content M a n
ASCII 77 97 110
Bit pattern 0 1 0 0 1 1 0 1 0 1 1 0 0 0 0 1 0 1 1 0 1 1 1 0
Index 19 22 5 46
Base64-encoded T W F u

Since in Base64 you can have totally 64 different characters so your output can have characters only from the set given below:
A-Z, a-z, 0-9, +, /
Note: last two character might change depending on the implementation, for example, in variant Base64 with URL and Filename Safe Alphabet (RFC 4648 'base64url' encoding) -(hyphen) and _ (underscore) are used.

There are many variants of base64 are available, Some are listed below:
  1. RFC 1421
  2. RFC 2045- org.apache.commons.codec.binary.Base64 class does encoding and decoding as per this standard.
  3. RFC 3548
See more exhaustive list here(Wiki).

Last thing we will cover in theory is padding.. Now padding is adding extra bits/bytes/characters etc. when required. In Base64encoding also, padding is required some times.

When does padding is done in Base64Encoding and what characters are inserted for padding?
I will not explain how padding is done. this is clearly explained on Wiki site of Base64(See Relevant References) here. Padding is done when the number of bytes to encode is not divisible by 3, that is there are only one or two bytes of input for the last block. The '==' sequence indicates that the last group contained only 1 byte, and '=' indicates that it contained 2 bytes (you'll like that there are implementations available which doesn't require padding at all).

There are various implementations available as I mentioned earlier but being a good developer you should open your eyes and decide which implementation to choose depending on the requirement. Some Common applications of Base64 are given below:
  1. URL:
    • To encode the URL query parameters
    • To encode data in hidden form fields
    • Just to obfuscate the URL data
  2. File names: Variant Modified Base64 for file name uses '-' instead of '/', because Unix and Windows file names cannot contain '/'.
Checkout the other applications also.

Let us jump to Base64 Encoding in Java: There are many implementations available. I will list them down first (not all):
  • Apache commons: org.apache.commons.codec.binary.Base64. Usage of this implementation is recommended.
  • Sun misc package: sun.misc.BASE64Decoder. Avoid using it as misc package is never officially released by SUN, this is one thing. Another thing is Oracle might be tempted to remove all packages with names having SUN and you see that code suddenly stopped working in future releases of Java.
  • Base64 class shipped with JAXB framework. Use this if your project is already using JAXB.
  • javax.mail.internet.MimeUtility: This class also has encode and decode methods and can do the job for you. But use them when your code is dealing with emails as this implementation follows MIME protocol guidelines.
There are many others also available. You can write your own as well (all the best if you are doing.)

Now it's time for demo code:
import java.util.Arrays;

import org.apache.commons.codec.binary.Base64;

/**
 * @author java-espresso
 * This class has two methods one encodes a string in Base64Encoding 
 * and other decodes the same.
 */
public class CommonUtil {

 public static String base64Encode(String stringToEncode){
  byte [] stringToEncodeBytes = stringToEncode.getBytes();
  return Base64.encodeBase64String(stringToEncodeBytes);
 }
 
 public static String base64Decode(String stringToDecode){
  byte [] decodedBytes = Base64.decodeBase64(stringToDecode);
  return new String(decodedBytes);
 }
 
}
Test class for the above code:
public class TestBase64 {

 /**
  * @param args
  */
 public static void main(String[] args) {
  String testString1 = "test String"; //Total bytes=11 divide by 3  and 2 bytes are in remainder so '=' is appended in the encoded string
  String testString2 = "TestString"; //Total bytes=10 divide by 3  and 1 bytes are in remainder so '==' is appended in the encoded string
  String testString3 = "Test string."; // Total bytes=12 divide by 3  and 0 bytes are in remainder so nothing is appended
  
  String encoded1= CommonUtil.base64Encode(testString1);
  String encoded2= CommonUtil.base64Encode(testString2);
  String encoded3= CommonUtil.base64Encode(testString3);
  
  System.out.println("====== Encoded Strings =======================================");
  System.out.println(testString1+" > Encoded > "+encoded1);
  System.out.println(testString2+" > Encoded > "+encoded2);
  System.out.println(testString3+" > Encoded > "+encoded3);
  
  System.out.println("====== Decoded Strings =======================================");
  System.out.println(encoded1+" > Decoded > "+CommonUtil.base64Decode(encoded1));
  System.out.println(encoded2+" > Decoded > "+CommonUtil.base64Decode(encoded2));
  System.out.println(encoded3+" > Decoded > "+CommonUtil.base64Decode(encoded3));
 }

}
output on executing the above code:
====== Encoded Strings =======================================
test String > Encoded > dGVzdCBTdHJpbmc=
TestString > Encoded > VGVzdFN0cmluZw==
Test string. > Encoded > VGVzdCBzdHJpbmcu
====== Decoded Strings =======================================
dGVzdCBTdHJpbmc= > Decoded > test String
VGVzdFN0cmluZw== > Decoded > TestString
VGVzdCBzdHJpbmcu > Decoded > Test string.
Please find the source of the application attached here.
Related Article

Relevant References

Thursday, October 13, 2011

Threads Part1: An introduction

A thread in computer science is short for a thread of execution. A thread is a single sequential flow of control within a program (i.e., process). Threads are a way for a process to split itself into multiple simultaneously running tasks. Threads are lightweight processes because they run within the context of a full-blown program and takes advantage of the resources allocated for that program and the program's environment. Threads are similar to process, but differ in the way that they share resources.
Java virtual machine can support many threads of execution at once. These threads independently execute code that operates on values and objects residing in a shared main memory. Threads may be supported by having many hardware processors (where threads are executed on separate processors), by time-slicing a single hardware processor (where a single processor switches between different threads giving the illusion that they are all executing at the same time), or by time-slicing many hardware processors. There is always at least one thread within every Java program: the main() method of the class which was given as a parameter to the Java interpreter.

Difference between a user thread and daemon thread. The daemon threads purpose is to give services to the user threads which are created by the user to perform the long running task (mostly for not blocking the ui or to do something in background ).The main() method of the application is a user thread. Threads created by a user are user thread ,you can also create the Daemon thread by explicitly calling the setDaemon(true) on a Thread object.One important point here is that setDaemon() method must be called before the thread is started .Once all the user threads are terminated then only JVM will terminate not in the other way if there are Daemon threads running but no user threads then JVM will close the running application .There should be atleast one user thread(main thread is a user thread )running for the JVM not to close the application.


There are two ways of implementing threading in JAVA
1) By extending java.lang.Thread class, or
2) By implementing java.lang.Runnable interface.
Before we go into implementation details I just like to cover when we use thread? so we use thread if we want some part of code is executed parallel and we put that code inside run() method of either Thread class or Runnable interface.
Actually public void run () method is defined in Runnable interface and since java.lang.Thread class implements Runnable interface it gets this method automatically.


//implementing Thread by extending Thread class
class MyThread extends Thread{
public void run(){
System.out.println("I am executing by Thread: " + Thread.currentThread().getName());
}
}

//implementing Thread by implementing Runnable interface
class MyRunnable implements Runnable{
public void run(){
System.out.println("I am executing by Thread: " + Thread.currentThread().getName());
}
}
//starting Thread
Thread mythread = new MyThread();
mythread.setName("T1");
Thread myrunnable = new Thread(new MyRunnable(),"T2");
mythread.start();
myrunnable.start();


Thread will not start until you call the start() method of java.lang.Thread class. When we call start () method Java Virtual machine execute run () method of that Thread class into separate Thread other than calling thread. Anybody guess what will happen if we call the run() method directly instead of calling start() method ?
run() method will simply be executed in the same Thread and new Thread will not be created. Another follow up question would be what will happen if you call start () method twice in same Thread object e.g

mythread.start();
mythread.start();// this line will throw IllegalThreadStateException


Difference between mythread.start() & mythread.run()?
• If we call mythread.start(), it will create a new Thread and that thread is responsible for execution of run().
• If we call mythread.run(), no new thread will create, the main thread only will execute run(), just like a normal method.
• In case of mythread.start() output we can’t expect
• In case of mythread.run() output first it ll run the code in the run function in the main thread .
Thread class start():-

public void start()
{
1. Registering our thread with the thread scheduler then only thread scheduler allocate CPU and memory type of resources for this new thread also.
2. calls run() // you can think of it as a call back invoked by the jvm
}



The thread is in the "new" state, once it is constructed. In this state, it is merely an object in the heap, without any system resources allocated for execution. From the "new" state, the only thing you can do is to invoke the start() method, which puts the thread into the "runnable" state. Calling any method besides the start() will trigger an IllegalThreadStateException.

The start() method allocates the system resources necessary to execute the thread, schedules the thread to be run, and calls back the run() once it is scheduled. This put the thread into the "runnable" state. However, most computers have a single CPU and time-slice the CPU to support multithreading. Hence, in the "runnable" state, the thread may be running or waiting for its turn of the CPU time.
The thread enters the "not-runnable" state when one of these events occurs:
The sleep() method is called to suspend the thread for a specified amount of time and yield control to the other threads.

The wait() method is called to wait for a specific condition to be satisfied.
The thread is blocked and waiting for an I/O operation to be completed.
For the "non-runnable" state, the thread becomes "runnable" again:
If the thread was put to sleep, the specified sleep time expired or the sleep was interrupted via a call to the interrupt() method.
If the thread was put to wait via wait(), its notify() or notifyAll() method was invoked to inform the waiting thread that the specified condition had been fulfilled and the wait was over.
If the thread was blocked for an I/O operation, the I/O operation has been completed.
A thread is in a "dead" state, only when the run() method terminates naturally and exits.

The method isAlive() can be used to test whether the thread is alive. isAlive() returns false if the thread is "new" or "dead". It returns true if the thread is "runnable" or "not-runnable".
JDK 1.5 introduces a new Thread.getState() method. This method returns an enum of type Thread.State, which takes a constant of {NEW, BLOCKED, RUNNABLE, TERMINATED, WAITING}.
NEW: the thread has not yet started.
RUNNABLE:
WAITING:
BLOCKED: the thread is blocked waiting for a monitor lock.
TIMED_WAITING: the thread is waiting with a specified waiting time.
TERMINATED:

Methods in Thread Class
The methods available in Thread class include:
public void start(): Begin a new thread. JVM calls back the run() method of this class. The current thread continues.
public void run(): to specify the execution flow of the new thread. When run() completes, the thread terminates.
public static sleep(long millis) throws InterruptedException: Temporarily suspend the thread and yield control to other thread for the given milliseconds. Method sleep() is thread-safe as it does not release its monitors. The method throws InterruptedException if it is awaken before the specified timing (via a call to interrupt() method). This is a static method and commonly used to pause the current thread so that the other threads can have a chance to execute. For example:
try {
// suspend for 0.1 sec and give other threads a chance to run
sleep(100);
} catch (InterruptedException ex) {}
public void interrupt(): Interrupt the sleep() method.
public boolean isAlive(): Return false if the thread is new or dead. Returns true if the thread is "runnable" or "not runnable".
public void setPriority(int p): Set the priority-level of the thread, which is implementation dependent.
public void yield(): suspend the current thread to allow other threads to run.
The stop(), suspend(), and resume() methods have been deprecated in JDK 1.4, because they are not thread-safe, due to the release of monitors. See JDK API documentation for more discussion.

What is the difference between implementing Runnable and extending Thread?
One difference between implementing Runnable and extending Thread is that by extending Thread, each of your threads has a unique object associated with it, whereas implementing Runnable, many threads can share the same object instance.
"Which way of implementing Thread is better? Extending Thread class or implementing Runnable method?

In my opinion implementing Runnable is better because in Java we can only extend one class so if we extend Thread class we can not extend any other class while by implementing Runnable interface we still have that option open with us.
Second reason which make sense to me is more on OOPS concept according to OOPS if we extend a class we provide some new feature or functionality , So if the purpose is just to use the run() method to define code its better to use Runnable interface.
e.g


public class Espresso {
public static void main (String[] args) {
Runner r = new Runner();

Thread t1 = new Thread(r, "Thread A");
Thread t2 = new Thread(r, "Thread B");
Thread s1 = new Mythread("Thread C");
Thread s2 = new Mythread("Thread D");

t1.start();
t2.start();
s1.start();
s2.start();

}
}

class Runner implements Runnable {
private int counter;
public void run() {
try {
for (int i = 0; i != 2; i++) {
System.out.println(Thread.currentThread().getName() + ": "
+ counter++);
Thread.sleep(1000);
}
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
}

class Mythread extends Thread {
private int counter;
Mythread(String name) {
super(name);
}
public void run() {
try {
for (int i = 0; i != 2; i++) {
System.out.println(Thread.currentThread().getName() + ": "
+ counter++);
Thread.sleep(1000);
}
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
}


output
Thread A: 0
Thread B: 1
Thread C: 0
Thread D: 0
Thread C: 1
Thread B: 2
Thread A: 3
Thread D: 1

Tuesday, October 11, 2011

JQuery Tutorial 1: Showing alert popup

Let me put the code first then we will do the post mortem

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.2.js"></script>
</head>
<body>
<input type="button" value="Trigger Alert" id="btn_trig">
<script type="text/javascript">
/* $('#btn_trig') gives reference to the html element whose id is passed,
 * similiar to getElementById() function. On that reference a callback function is defined
 *  syntax of callback functions is like this event( function(){ //thing you want to do on event happening}). Callback functions are called when event happens.
 *  
 */
$('#btn_trig').click(function(){
 alert("Hello World!");
} 
);
</script>
</body>
</html>

Try for yourself:



Thursday, September 29, 2011

Configuring SSL in tomcat

What is SSL?
SSL or Secure Socket Layer is a technology which allows web browsers and web servers to communicate over a secured connection. The data being sent is encrypted by one side, transmitted, then decrypted by the other side before any further processing. Essentially, it is a two way process, Browser encrypts its requests before sending them to the server and server decrypts them then server encrypts the response and the browser decrypts it.

There is one more thing we should understand about SSL is certificates used for Authentication. When the Browser places the first request to a web server over a secure connection, that server will respond to your web browser with two things, one is your page (for example ICICI Loginpage,CitiBank login page) and other is a set of credentials, in the form of a Certificate; This certificate gives information to the browser about the authenticity of the website.

Certificates and SSL
In order to implement SSL, a web server must have an associated certificate for each external IP address that accepts secure connections. Certificate acts as a identity proof for the website like your passport for you. This certificate is signed by the issuer (you can also create your self-signed certificates as well, but do not use them in production). Issuer is normally a well recognized authority like VeriSign, Thawte, Go Daddy, etc.

Why shouldn't you use Self-signed certificates?
Hackers normally utilize the weakness of your certificate to attack and the weakness is that it is self-signed. The attack might happen, something like this, when the client attempts to connect to the server the hacker hijacks the connection(means that now your requests will go to the hacker not the server). He then sends the client his own self-signed certificate(seeing which you feel happy and say, wow, now I can fill my credit card info without any prob.) which has the same name as the one present in the server's self-signed certificate. The hacker then connects to the real server himself. When the client sends data to the server the attacker reads it(might change it as well) and then sends it along to the real server. So, your credit card information might get leaked.
Let us start with tomcat:
  1. You need to create a keystore file to store the private key of the server using the following command.
    Windows:

    Unix:

    Same is shown below:
    The file will get created under the directory from which you are running the command, for example, as shown in image, the file will get created under following path: C:\Users\dharmvir.singh

    To specify a different location to store the keystore file(keystore in the last of the path), just modify the above command as shown below:
    Windows:

    same way you can do in unix.
    Sample is shown below:
    Password used in both the example screens shots is "changeit" as it is the default password for tomcat.
    The certificate can be obtained from authorities like Verisign and others.
  2. Uncomment the following section from $CATALINA_HOME/conf/server.xml:
    
    
    $Catalina_Home here represents path of your tomcat home folder
To test it I created a sample TestServer app (I have attached tomcat with that application to download). Here is how it will look like on accessing it on localhost.
Tips on SSL:
  1. SSL has encryption/decryption which is expensive so do not configure entire application on SSL. For example, Website home, adds, banners pages, sitemap page, about us page might not be put on SSL.
  2. using name-based virtual hosts on a secured connection can be problematic. This is a limitation of SSL protocol. So you can use only one certificate for one IP address.

Apache-Troubleshooting SSL in tomcat

tomcat with SSL enabled can be downloaded from here, It contains the TestServer App as well, so just download and start the server and test it.

Relevant References

Note from Author: Please leave appreciation comment, if you like the article or else please leave your questions, suggestions or feedback.
Thanks,
java-espresso

Wednesday, September 28, 2011

JAVA BASICS.. JAVA A DIFFERENT APPROACH TO START.. JAVA PLATFORM INDEPENDENT. HOW JAVA IS PORTABLE?


Must read for a good start of JAVA

All of us know that JAVA is portable i.e JAVA is platform independent.Let us try to figure out the reason how Java is platform independent. Java has used a slogan Write Once Run anywhere.

Explanation:
Some language generate .obj or .exe file after compiling. These generated file will not work in other Operating system. There was a need to have something which will not depend on operating system. Hence they came with new concept of JAVA VIRTUAL MACHINE(JVM). Running a java program was divided into 2 parts. First part makes .class file and in the second part this .class file will be run on JVM.
For the generation of .class file from .java file,compiler was written which will always generate the same .class file for any of the operating systems. Half of the work is over for getting platform independency.

.java ----Compile---->.class(Byte Code)---Interpreter(Platform Dependent)--->machineCode


For running the same .class file in different OS, they made a difference in JVM for different operating system. JVM depends on the hardware and OS architecture. It will take .class file as input and interpret it. So for the same .class file it will generate the same output. It is the difference in JVM which has made java a platform independent language.

Now in the next post we will learn basics of java taking memory into consideration.

Friday, September 23, 2011

web.xml servlet Understanding <url-pattern>/*</url-pattern>

Understanding the <url-pattern>/*</url-pattern>

Other Questions of similar pattern:
1) How to exclude from url-pattern in servlet mapping?
2) To exclude content from url-pattern

While developing web.xml in application, do take care of the <url-pattern>.
Try not to give a generic url-pattern ie., <url-pattern>/*</url-pattern>.The disadvantage of this URL Pattern is, any request coming to the server will fall in this URL PATTERN(except for those you have explicitly defined). Suppose browser is requesting a page which has images,css,etc then you will find page will load with the servlet response,while the images,css,js,etc are not getting loaded and it will be very difficult to find the reason for this type of behaviour.

The reason is as:-
Our browser requests in the following steps
Step1: The browser requests the page and gets back the response which contains all other path.
Step2: The browser again requests all the other path to the server and these path contains the images,css,etc

What happens in our problem is in step 2,the browser's request goes to the server and now the images,etc also falls in the <url-pattern >/*</url-pattern>,which redirects to a servlet and this is the problem. This is the reason why we don't get images and other files in our web page.

Let us solve this with the help of example:
web.xml

 TestUrlPattern
 
   ServletDefault
   com.test.ServletDefault
   
  
    ServletDefault
    /*
  
  
  abcd
  /abc.jsp
  
  
   abcd
    /abc.jsp
  


abc.jsp
<html>
<head>
<title>TestUrlPattern</title>
</head>
<body>
Sample text
<img src="Desert.jpg" >
</body>
</html>


Whenever a request comes as localhost:8080/TestApp/abc.jsp, the abc.jsp loads and images are not getting loaded. The images goes to the SevletDefault mapping. You can see this by printing any text in doGet or doPost method of ServletDefault class.
Reason is,all files other than abc.jsp will go to ServletDefault.

Solution for /* type pattern in web.xml

I found two approaches to solve this problem
Approach 1:

Make a common servlet which consumes all the files which have the pattern for images,css,javascript,etc
web.xml  (modified)

  TestUrlPattern
  
      CommonServlet
      com.test.CommonServlet
    
  
      Servlet
      com.test.Servlet
    
    
        Servlet
        /*
    
    
    abcd
    /abc.jsp
  
    
    
      abcd
        /abc.jsp
    
        
        CommonServlet
        /images/
    
    
        CommonServlet
        /stylesheet.css
    
    
        CommonServlet
        /javascript.js
      


Keep the images in the 'images' folder. For a new request to the servlet, you will find,all the images,css,js requests goes to CommonServlet. Write a CommonServlet which retuns back the file itself in the response.

CommonServlet.java

public class CommonServlet extends HttpServlet  {
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  ServletContext sc = getServletContext();
  String path=req.getRequestURI().substring(req.getContextPath().length()+1, req.getRequestURI().length());
     String filename = sc.getRealPath(path);

     // Get the MIME type of the image
     String mimeType = sc.getMimeType(filename);
     if (mimeType == null) {
         sc.log("Could not get MIME type of "+filename);
         resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
         return;
     }
     // Set content type
     resp.setContentType(mimeType);

     // Set content size
     File file = new File(filename);
     resp.setContentLength((int)file.length());

     // Open the file and output streams
     FileInputStream in = new FileInputStream(file);
     OutputStream out = resp.getOutputStream();

     // Copy the contents of the file to the output stream
     byte[] buf = new byte[1024];
     int count = 0;
     while ((count = in.read(buf)) >= 0) {
         out.write(buf, 0, count);
     }
     in.close();
     out.close();
 }
}

The above servlet write the contents of file in the response and our problem is solved.

Approach 2:

This approach sets the context in jboss server.xml file.
server.xml is found at Jboss_home\server\default\deploy\jboss-web.deployer path.
Open server.xml in edit mode
Add the context in server.xml.
Find text similar to the following code in server.xml
<Host name="localhost" autoDeploy="false" deployOnStartup="false" deployXML="false"configClass="org.jboss.web.tomcat.security.config.JBossContextConfig" >
Below the above code add the context as:



set docBase,path according to your path.This will solve your problem.

These were the two approaches which i found out for this problem. Please let me know if you know any more approach.

4.JAVA BASICS.. IS JAVA A PURE OBJECT ORIENTED LANGUAGE..PROBLEM SOLVING.


As you all know java is a pure Object Oriented language.
Is java Really a pure Object Oriented Language?

The answer is NO..Java is not a pure object oriented language.
1)The main reason for this is it does not always deal with objects.
int,char,float,etc are not in the form of objects and java uses them. So this is the main reason why java is not object oriented language.
2)The other reason is that java does not support Multiple inheritance in case of classes,but a pure object oriented language supports multiple inheritance.

Now let us see some of the basic thing in java which is to be noted. Those who already know java can skip this.

What is the default value of Byte?
Ans: NULL

Now a question may arise in your mind,that the default value of byte is false.Your question is correct.
If you observe clearly,then you will find that default value of Byte is asked not byte.And Byte is a class that means it will store reference. Remember in the first java basic, i told to see the data types start with lower case.

Point to be remembered: In java a class is always declared with first letter as Upper case letter(This is not a rule but it is a best practice so that you never make mistake).

Similarly you will find some more class which may confuse you like Boolean with boolean ,Float with float,Double with double. So don't get confuse with these classes.

 Now a question may arise in your mind that why they have made these confusing classes.What is the use of these classes.Your question is correct,following is the explanations for this.

Sometimes we need objects of these primitive data types,for this Java has made WRAPPER CLASSES for these primitive data types. All the primitive data types have Wrapper Class. Now by using these Wrapper classes,we can convert these data types to Objects and can use them.
Following are the wrapper classes of the primitive data types
1)int    --> Integer
2)byte   -->Byte
3)short   ---> Short
4)char    --->Character
5)boolean  --> Boolean
6)float    --->Float
7)double   --->Double
8)long     --->Long
9)void    ---> Void

Compilation of program:
The java compiler search for a particular signature in the main function.
The signature is
public static void main(String[] args)
This is the signature,that should exist in a program to run ,otherwise it will not run.

Example for the above concept
Class A
{
public static void main(String[] args)
{
     main('x');
     System.out.println("my string");
}
public static void main(char b)
{
     System.out.println(b);
}
}

Output: x
            my string

Reason: It will only treat the first main method as the main method as it is having proper signature and treats 2nd method like a normal java method.

Example2:Count how many objects are created and how many references exist:

Eg:
Customer a=new Customer();
Customer b=new Customer();
Customer c=a;
Customer d= b;
new Customer();

Ans: 3 Objects 4 references

In these types of questions just count the number of new keywords that will give you the number of objects.
and count the number of references by the class name count and in some examples please make the heap and object diagram which we made earlier and then there will be no mistakes.

In next we will learn the concept of static in java..So keep reading...

3.JAVA BASICS.. CLASS AND OBJECTS WITH APPROACH OF MEMORY

What is a class?
We can say class is a template of an object. Objects exists in memory. Class is just a way to define a structure of object.

Now we start with discussion of memory.
Four segments of memory
1)Data segment
2)Code segment
3)Stack segment
4)Heap segment

In C we have seen the use of code and data segment. But in java we will be dealing with Stack Segment and Heap Segment.

See the example below

When we write using new keyword, a new object is created and new Customer() returns the hashcode of the created object. The variable used to store the hash code value is called reference variable.It is called reference because it has the hash code value,which refers to an object.

In short we can say that obj(the variable used above) stores the hash code,where hash code is not the actual address(it is changed to hash code by some hash algorithm). Java does not deal with direct memory,it deals with hash code and the hash code  indirectly refers to a memory. This is the reason why java is called secure. Unlike C,it has no pointers or depointers which can take you to the actual memory address.

Suggestions: 
When ever dealing with output problems,always make a heap by making a square and see the code for how many objects are there. Count and make that many ovals inside the square and point these objects by an arrow of reference. I assure you by using this method,you will not make any mistakes. Example is below

Now an important note,to be always kept in mind and will solve all your problems.
         Local Variables   ------->  STACK
         Global Variables  ------->   HEAP
Keep the above note always in your mind and there will never be a chance of mistake.Here global refers to be a part of class definition.
Stack Variables do not have any default value
Heap variables have default value. If there is any variable in Stack and you try to use that variable without initialization then it will result in a compile time error.
All the objects which are created using new keyword,goes to heap memory,while the location of these references depends,whether they are local or global.
    Take a simple example::
  Sample sample=new Sample();
Here the object of class Sample will always be in heap memory,while the reference(sample here)  location depends on whether it is declared locally or global. We can say that if sample is inside a method then it will be in stack,and if it is inside a class(but outside methods) then it will be stored in heap memory.

Default values of all the variables(only Heap Variables)
int       ---> 0
byte     --->0
short    --->0
boolean -->false
long    ---->0
float     ---->0.0f
double  ---->0.0
char     ----->'\0'
Reference Variable   ---> NULL

NOTE: From above,keep in mind,all variables  keep 0 as the default value.. false(boolean) can be related with 0,NULL can be related with 0,'\0' can be related with 0. Keep in mind a default value of 0.

By seeing any class you can relate the variables with stack and heap.

We will do some examples and then proceed
Class Sample{
int a;                //   Global Variable =>heap              
void printVariable()
{
int b;               //     Local Variable => Stack                 
System.out.println(a);
System.out.println(b);                         ///Error
}
}

Why Error?
The reason is that b is a local variable. We are trying to use a local variable,which is not initialized,and stack variable don't have  default value so it gives error. 
Comparison with C language: In C also,global variables prints 0 while the local variable gives Garbage Value.
Java does not want to have these garbage values because that will make your code buggy,so Java compiler is checking for this at compile time only and thus ,doesn't allow the code to compile.

Example 2:
Class Sample{
Test obj;            //   suppose Test is another class
int a;
void printVariables()
{
System.out.println("value of a is:"+a);
System.out.println("value of reference:"+obj);
}
}
Ans: As we can see that both are global variables,means both use heap memory.
None of them is initialized,so default value is printed.
    value of a is: 0
    value of reference: NULL

Example 3:
class Sample{
void printArea()
{
 int a;
int b=1;
if(b==1)
{
a=10;
}
System.out.println(a);
}
Ans: Compile Time Error
Now the question that come in your mind, the local variable is initialized before using,then why it gives compile time error.
Reason: Even though you have initialized the variable,but at compile time, the compiler does not know in advance if it will enter the loop or not at run time. If suppose,at run time it does not enter the loop and the variable will not get initialized. To avoid these type of situations at run time,java is designed such a way,if a variable is not initialized and gets initialized in inner loops,it does not matter. So if any variable is initialized in inner loop but not in the loop where it is declared,and we use the variable in the declaration loop,the code will not compile.

2. JAVA BASICS..JAVA PRIMITIVE DATA TYPES.. A CORRECT WAY TO START JAVA


There are 8 primitive java data type

We will write the java data types in increasing order of their size (in bytes).

boolean<byte<short ,char <int,float<long,double
    (1)        (1)        (2)            (4)            (8)

 Please notice, all data type start with a lowercase letter.
We will derive the possible values of these data types,according to the size of data type.

byte: memory =1byte=8 bits
 1(signed bit)   1    1    1    1    1    1    1  
                                           7       6    5     4     3     2    1   0
Our computer store numbers in 2's complement format.

Calculating the max value.
Signed bit=0 for positive number.Below is the format shown


 0(signed bit)   1    1    1    1    1    1    1  
                                           7       6    5     4     3     2    1   0

max value :
 (0*27)+26+25+24+23+22+21+20
       => 127
       => 27-1

Min value:
Taking the signed bit as 1, i.e negative number. For getting lowest -ve we make all other bits to 0
Below is the format shown

 1(signed bit)   0    0    0    0    0    0    0  
                                           7       6    5     4     3     2    1   0

Calculated value is     (-27)
    => -128

The range of byte  as derived is: -27 to (27-1)      OR  -128 to 127

Analyse the above in powers of 2. You will find that for 8 bits it comes to power 7.

short:
  size=2 bytes= 16 bits

 1(signed bit)   1    1    1    1    1    1    1    1    1    1    1    1    1    1    1  
       15             14  13   12  11   10   9    8     7    6     5    4     3    2     1     0

max value:

 0(signed bit)   1    1    1    1    1    1    1    1    1    1    1    1    1    1    1  
      15             14  13   12  11   10   9    8     7    6     5    4     3    2     1     0

Calculated value:
      =>        20+21+22+.............+214 {Geometric progression formulla a(rn+1-1)/(r-1)}
here a=1,r=2,n=14
     => 1+21+22+......214
     => (215-1)

Min Value:
 1(signed bit)   0    0    0    0    0    0    0    0    0    0    0    0    0    0    0  
       15             14  13   12  11   10   9    8     7    6     5    4     3    2     1     0

calculated value:   -215

Range: -215 to (215-1)      OR -32768 to 32767

Here 2 bytes=16bits -----> Range in power of 15

char:
Don't consider the signed bit here as characters cannot be -ve.
Java follows unicode characters,and cannot be placed in 1 byte as 1 byte can contain a max of 255 chars.

max value:

 1   1    1    1    1    1    1    1    1    1    1    1    1    1    1    1  
           15   14  13   12   11  10   9    8     7    6     5    4     3    2     1     0
All 1's
   => 20 +21+......+215
   => (216-1)
   => 65535


Min Value:  all 0's
    => 0
Range: 0 to 65535

We can say,char supports a max of 65535 characters.

int:
 4 bytes=32 bits
See the above derivation for short,byte and you will be able to write the range of integers.
The range comes  -231 to (231-1)

long:
8 bytes=64 bits
Range:   -263  to (263-1)

From the above discussion,it is clear,we don't have to learn these ranges,just calculate the number of bits and you will be able to write the range directly without any calculation.

float(Calculation for float range)
It follows IEEE 754 standard.
According to which 1 bit is fixed for sign. 23 for Mantissa and 8 bits for Exponent


 1(signed bit){s}  <------23 bits(Mantissa)--------> {M}   <----8 bits(Exponent)--->{E}  

Formula for Calculation of Value is:
         =>  (-1)s * M* BE
where base B is fix by designer.

Mantissa is assumed to be in decimal i.e its value start from 1.{caculated value}
M=1.{calculated Mantissa value}

Assume,all mantissa bits to be 1:
Calculated value is:   2-1+2-2+.....+2-23  = 1-2-23=    0.999999880790071044921
Mantissa is: 1.999999880790071044921
Exponent is stored in excess 127 format. E is 8 bits. No signed bit in exponent,calculated range is 0 to 255.
Actual range is calculated by subtracting 127 from stored exponent value. Values 0,255 are fixed for special purpose. As M=1.{some value}, it can never be 0, and also the number cannot be 0. For this reason 0,255 were fixed for special purpose, which otherwise are not possible. Following are the special cases.
a) If M=0,E=0    => Number is 0
b) If  M=0, E=255   => Number is +ve Infinity
c) If M={any value} ,E=0 => Number is -ve Infinity
d) If M={any value}, E=255  => NaN(Not a Number)
Actual range of Exponent(subtracting 127 and not taking special case value): -126 to 127

Max Value(positive)= 1.999999880790071044921 * 2 127
=>3.40282346638528860e+38  (calculated  from calculator)

Min Value  : -ve of Max Value

Float range : (-1.999999880790071044921 * 2 127)    to 1.999999880790071044921 * 2 127
OR  -3.40282346638528860e+38    to     3.40282346638528860e+38

Minimum positive value= 1* M * 2 -126
 => 1.75494e-38 (M=1 for making it the smallest possible positive number,which means all the mantissa bits are 0)

The positive values range from 1.75494e-38 to 3.40282346638528860e+38
Range Magnitude Minimum(Denormalized) 
  { Here,they take min value as 2E(min)-no. of mantissa digits}
=1* 2-126-23
=>  2-149
=> 1.4012 e -45


We can say that min positive number is 1.4012 e -45.
Positive number range is 1.4012 e -45  to   3.40282346638528860e+38     -->(1)
Similarly maximum -ve number possible is (-1.4012 e -45)
Similarly,-ve number range is (-3.40282346638528860e+38) to (-1.4012 e -45)      --->(2)

The derivations (1) and (2) are the ranges which you will find in text books.This denotes the minimum possible positive number and also the minimum possible difference between 2 numbers. Similarly we can calculate the maximum possible difference by calculating the difference between the largest possible number and the 2nd highest possible number.

double:
8bytes=64 bits
Mantissa - 52 bits
Signed -1 bit
Exponent- 11 bits

Same as the above method,we can calculate the positive and negative range for double.
I have not calculated,i am writing the book range
 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative).
But the method is similar.
Please calculate once.


TYPE CONVERSION
Now think type conversion in simple terms.
If we try to save information from more number of bits space to a smaller number of bits space. 
Is this possible?? Ask the question to yourself.
Not satisfied.
Try to save 111111111111111 in 8 bits. It is obvious that some bits will be lost.
Think the other way around try to save 8 bits in 16 bits. It is easily possible without loss of information.

To avoid this problem the java designers thought,the loss of information should not happen. They fixed ,you cannot convert from higher to lower but lower to higher is allowed.
But in explicit it is possible to convert from higher to lower,which means that you agree for loss of information.

Below you find the lowest to highest (one way)
byte<short,char<int<long<float<double.

You will find that  long(8 bytes) and float(4 bytes).
Now you will ask how is it possible.
See the highest value possible for long which is (263-1) while the highest possible value for float which is 1.999999880790071044921 * 2 127 
which is much more than max possible value of long. There will be loss of precision but the value can be stored in that.
This is how the type conversion works.

EXAMPLES
Now we will see few examples and try to learn the type casting.
=> In java,default decimal values are treated as double.

1)int a=10.1;

The above code will give Compile time error.. Why??
RHS is of type double and LHS is of type int. So we are trying to save big in a small one.Is it possible?
No Bigger data type to  smaller data type is not possible.

2) float b=7.2

The above code will give Compile time error.. Why??
RHS is double and LHS is float. Bigger data type to  smaller data type is not possible.

3) byte b=10,c=20;
byte d=b+c;

The above code will give Compile time error.. Why??
The reason behind this is that the arithmetic calculations are treated as integers in java.
So b+c is an integer and this integer value we are saving in byte which is not possible
so correct way is byte d=(byte)(b+c)


Eclipse connection through proxy server for update

Most of the companies have proxy server in between internet and your computer.For update we need connect to internet but the proxy server requires authentication for that. And we are not able to connect to internet through Eclipse.

Solution to the problem.

Step 1)If you know the proxy server name and port number then go to step 2. If you don't know the proxy settings then open internet Explorer.Go to tools->Internet Options->Connections(Tab)->LAN settingsYou will see something as follows




Out of three check boxes may be only one is checked.
Find the check box which is checked
a) If the first check box is checked then there is no proxy required
b) If the second is checked copy the URL for "pac" file and open in a browser and download it and then open it. There may be many servers with ports defined in the file. You can choose any one. I chose the last one with IP address and port number. This is how you will get proxy server and port number
c) If the third is checked then you can directly take Address as proxy Server and port as port number.
In above image for example you can see the proxy server as sample/gate.net and port as 100

In this  step you get proxy server and port number.

Step 2: Open the Eclipse 
a) Go to Window->Preferences
b) Go to General tab -> Network Connections
 After this you may find one of the following screens depending on the version of Eclipse
Screen 1
Screen 2

i)Screen 1:  From the Active provider drop down Select "manual" then you will find 3 Check boxes as shown in screen 1 automatically gets checked. Now Double click on any of the checked Check Boxes a new small window will open where you will be prompted to enter Host, port, Username and password. 
In the host Text Field enter the proxy server name which we got in step 1 and also enter the port number.
In the username and password enter the user name and password you got from your company(it may be same as your desktop password). Repeat this for all three check boxes and click apply and then Ok.
So now you are done with proxy setting in eclipse.

ii) Screen 2: Click on Radio Button Manual proxy Configuration. You can directly see to enter the Http proxy,SSL proxy,SOCKS proxy. So enter here the proxy server and port number. Below you will find to enter User Name and password. Enter the desired user name and password and you are finish with the work.Click Apply and Ok

Now you can directly update the Eclipse with your proxy server also.
Please feel free to tell if there is anything wrong in this blog or any update is needed.

Wednesday, September 21, 2011

DES algorithm Code in Java

Introduction of DES
The Data Encryption Standard (DES) is a symmetric-key algorithm that uses a 56-bit key.Symmetric-key encryption means it uses same key to cipher and decipher the message. DES was developed in IBM under the name of LUCIFER. DES is now considered to be insecure for many applications(especially Govt., defense). For applications demanding more security of the content, Triple-DES can be used.

Coding DES in Java
Code listing below contains the Cryptography class which has both encryption and decryption method.
import java.io.IOException;
import java.security.InvalidKeyException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * @author dharmvir.singh 
 * The class demonstrates the DES algorithm by using java
 * crypto API
 */
public class Cryptography {
 private static final String CRYPTOGRAPHY_ALGO_DES = "DES";
 private static Cipher cipher = null;
 private static DESKeySpec keySpec = null;
 private static SecretKeyFactory keyFactory = null;
 
 public static String encrypt(String inputString, String commonKey)
   throws InvalidKeyException, IllegalBlockSizeException,
   BadPaddingException {
  String encryptedValue = null;
  SecretKey key = getSecretKey(commonKey);
  cipher.init(Cipher.ENCRYPT_MODE, key);
  byte[] inputBytes = inputString.getBytes();
  byte[] outputBytes = cipher.doFinal(inputBytes);
  encryptedValue = new BASE64Encoder().encode(outputBytes);
  return encryptedValue;
 }
 public static String decrypt(String encryptedString, String commonKey)
   throws InvalidKeyException, IllegalBlockSizeException,
   BadPaddingException, IOException {
  String decryptedValue = "";
// When Base64Encoded strings are passed in URLs, '+' character gets converted to space and so we need to reconvert the space to '+' and since encoded string cannot have space in it so we are completely safe.
  encryptedString = encryptedString.replace(' ', '+');
  SecretKey key = getSecretKey(commonKey);
  cipher.init(Cipher.DECRYPT_MODE, key);
  byte[] recoveredBytes = cipher.doFinal(new BASE64Decoder()
    .decodeBuffer(encryptedString));
  decryptedValue = new String(recoveredBytes);
  return decryptedValue;
 }
 private static SecretKey getSecretKey(String secretPassword) {
  SecretKey key = null;
  try {
   cipher = Cipher.getInstance(CRYPTOGRAPHY_ALGO_DES);
   keySpec = new DESKeySpec(secretPassword.getBytes("UTF8"));
   keyFactory = SecretKeyFactory.getInstance(CRYPTOGRAPHY_ALGO_DES);
   key = keyFactory.generateSecret(keySpec);
  } catch (Exception e) {
   e.printStackTrace();
   System.out.println("Error in generating the secret Key");
  }
  return key;
 }
}

Download
Code can be downloaded from here
Download contains:
  1. Cryptography.java: Contains the encrption and decryption method
  2. TestCrypto.java

Related Articles
Implementing MD5 in java

Relevant References
DES explained
Wiki Links:
DES, Symmetric-key algorithm, Triple-DES

Wednesday, September 14, 2011

MD5 encryption in Java

What is MD5?
MD5(Message-Digest algorithm 5)is hashing function which results in 128 bit(16 byte) hash value. It came as a replacement of MD4 which was considered insecure then. MD5 is one way encryption technique means once I have encrypted some text using MD5 I cannot get the clear text from the hash value again. But now it is proved that even MD5 is vulnerable.

Where can we use MD5?
MD5 can primarily be used for encryption and for checking file integrity. But again remember it is possible to have two big different files having same hash value.
Usage examples:
  1. Data Encryption:You can use it to encrypt your passwords something like getMD5Hash(password+date+time of registration)= 'hashed value'. Here we have concatenated actual passwords with date and time of registration to ensure that every time a unique hash value gets generated.
  2. File integrity: Suppose you want to make a file comparing utility. So if you will go straight away and compare the files it will not efficient. So first we can compare size, then HASH VALUE OF BOTH FILES(by using MD5 hashing) and if both are same then probably you can compare the actual text in the files.

Implementing MD5 in Java:
MD5 is already implemented in java. So we just need to reuse the method and do some pre and post processing. MD5 hashing technique always produces a fixed length encrypted string having 128 bits or 16 bytes and so you will always get a hexadecimal string of length 16.
Code listing is given below:
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;

/**
 * @author dharmvir.singh
 * @Description: This class generated the hash code of few strings
 * 
 */
public class TestMD5 {
 public static void main(String[] args) {
  String[] inputStrings = { "Open Source", "Apache project",
    "java espresso" };
  System.out.println("String\t\t\tHash Value\t\tHash val length");
  System.out.println("======\t\t\t==========\t\t===============");
  for (int i = 0; i < inputStrings.length; i++) {
   System.out.println(inputStrings[i] + "\t\t"
     + getMD5HashVal(inputStrings[i]));
  }
 }

 public static String getMD5HashVal(String strToBeEncrypted) {
  String encryptedString = null;
  byte[] bytesToBeEncrypted;
  try {
   // convert string to bytes using a encoding scheme
   bytesToBeEncrypted = strToBeEncrypted.getBytes("UTF-8");
   MessageDigest md = MessageDigest.getInstance("MD5");
   byte[] theDigest = md.digest(bytesToBeEncrypted);
                        // convert each byte to a hexadecimal digit
   Formatter formatter = new Formatter();
   for (byte b : theDigest) {
    formatter.format("%02x", b);
   }
   encryptedString = formatter.toString().toLowerCase();

  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  }
  return encryptedString;
 }
}
The code is self explanatory and I tested it already. For production purposes, avoid using MD5 as encryption technique for banking domain and (security concerned) domains.
Related Articles
Implementing DES in Java

Relevant References JBuilder Professional: Pure Java Visual Development With Integrated Database Tools

Tuesday, September 13, 2011

org.tigris.subversion.javahl.ClientException: RA layer request failed

Title of the article is basically an error which you might receive when you are trying to connect to a SVN repository over internet (that means repository is outside your corporate LAN firewall) using subversion plugin (inside Eclipse).
Below is the screen-shot of the same:

Now how to resolve it. Here we go:
  1. Close the eclipse if it is running.
  2. Open the following file:
    Windows Vista/7: C:\Users\<user-profile-name>\AppData\Roaming\Subversion\server
    Windows XP: C:\Documents and Settings\<user-profile-name>\Application Data\Subversion\server
  3. Go to the Entry shown below:
    [global]
    # http-proxy-exceptions = *.exception.com, www.internal-site.org
    #http-proxy-host = somehost.example.com
    #http-proxy-port = 80
    # http-proxy-username = defaultusername
    # http-proxy-password = defaultpassword
    
  4. Uncomment the http-proxy-host and http-proxy-port line and provide your proxy server path and port no. Do not leave any spaces before the http-proxy-host.So it should look like this:
    http-proxy-host = substitute with your proxy server path
    http-proxy-port = substitute your proxy server port
    

  5. Start the eclipse again.
  6. That should resolve the problem for you. If this article resolves your problem. Please leave a comment otherwise add comment to let me know, your issue.

After seeing so many comments, I decided that I will try the same thing for NetBeans and guess what it was easier than eclipse also.
Following are the steps to access the SVN behind the firewall:
  1. Click on Team > select subversion > select checkout...
    Click on the image to open it in new window to see it properly.
  2. On the next window fill the repository URL, username and password as shown:
  3. After that click on Proxy Configuration.. button and select Manual Proxy settings and fill the proxy server host and port and click on ok as shown:
  4. Note: If your company uses a .pac file for proxy settings then open that file and find out the proper proxy server address and port number. In NetBeans do not select the option of using system proxy settings
At times we make mistake in entering the URL itself so here is a sample SVN url
https://onlinerepository.com/svn/myproject

Saturday, August 27, 2011

Singleton Pattern in Java

In "Set Theory", A singleton set has always only one element, Similarly, Singleton class in Java has only one object. Sometimes it is the requirement to have only one instance of a class, for example, Logically you should have only one instance of 'Download Manager', 'Windows Task Manager' is only one, Factory class in Factory pattern has to be singleton, etc.

Common uses of Singleton pattern:
1. is used in other patterns like, Factory, Abstract Factory, Builder, Facade patterns etc.
2. is used in State Object pattern as state object
3. Is preferred over global variables as lazy initialization is possible with singleton objects.

Intent in Implementation:
1. Implementation should ensure that only one object gets created.
2. Global point of access should be there. Even global variables can be used for this purpose but Singleton has its own advantages.
3. Lazy initialization implementation (optional, if your application demands it implement it)

Why prefer Singleton over global variables?
Global variables could be resource intensive as they will acquire memory as soon as your application starts whereas Singleton initialization can be deferred.

Implementations:You will find many implementations of Singleton pattern available, we will try to cover the common ones.
  1. UML Diagram for the same is given below. This implementation does not use lazy initialization and provides global access to the object through static method

    Image Source: Wiki
    Code Listing 1
    /**
     * @author Dharmvir Singh
     *
     */
    public class Singleton {
    	/* restrict access using private modifier
    	 * Below variable will be initialised at the class loading time
    	 */
    	private static final Singleton singleton =  new Singleton();
    	// No one can create object from outside using the constructor
    	private Singleton(){}
    
    	// Below static method is global point of access
    	public static Singleton getInstance(){
    		return singleton;
    	}
    }
    
    Advantage of above implementation is it is thread safe.
    Disadvantages include deserialization issues,object gets initialized at the class loading time, In case of different class loaders, you might get different objects

  2. UML is same as above. We will slightly modify our above class to incorporate lazy initialization. So, We call our class "LazySingleton"
    Code Listing 2
    /**
     * @author Dharmvir Singh
     *
     */
    public class LazySingleton {
    	private static LazySingleton singleton ;
    	// No one can create object from outside using the constructor
    	private LazySingleton(){}
    
    	/* Below static method is global point of access
    	 * Object is created when the method is called for
    	 * the first time and then same object gets returned
    	 */
    	public static LazySingleton getInstance(){
    		if(singleton == null){
    			singleton = new LazySingleton();
    		}
    		return singleton;
    	}
    }
    
    Above implementation used deferred initialization but is not thread safe. To know what issues you might face in implementing Singleton in Java, see my article: Java Singleton Pattern: Breaking the pattern

    There are other implementations available as well. Let us see them as well
  3. Bill Pugh's solution: He provided a thread-safe solution. Here is the code listing
    public class Singleton {
       // Private constructor prevents instantiation from other classes
       private Singleton() {
       }
     
       /**
        * SingletonHolder is loaded on the first execution of Singleton.getInstance() 
        * or the first access to SingletonHolder.INSTANCE, not before.
        */
       private static class SingletonHolder { 
         public static final Singleton instance = new Singleton();
       }
     
       public static Singleton getInstance() {
         return SingletonHolder.instance;
       }
     }
    
  4. Singleton using Enum in Java:Joshua Bloch in the second edition of his book "Effective Java" has claims that "a single-element enum type is the best way to implement a singleton". Here is the code listing:
    public enum EnumSingleton {
    	INSTANCE;
    }
Why Singletons are bad
  1. Unit testing of singleton class and its dependent classes is difficult.Check out the discussion
  2. Singleton classes cannot be reused. For example suppose your controller in MVC is singleton, you cannot use it for any other purpose
  3. Singletons cannot be extended. For example, if you try to subclass a singleton, firstly you cannot, somehow if you figure that out you will land up in many other problems
Relevant References:
  1. Wiki
  2. JavaWorld:Singleton
  3. JavaBeginner:Singleton
  4. Use your singletons wisely

Wednesday, August 10, 2011

InfoQ: Big Data in Real Time at Twitter

InfoQ: Big Data in Real Time at Twitter