Monday, November 4, 2013

What is Java Web Start ( javaws.exe ) ?

Java Web Start is an application deployment technology that can be used to download and run java applications from the web . The download and installation can be done with a single step without going through the complicated installation process.

Java Web Start also caches the downloaded application on local machine so the subsequent invocations are instantaneous as all the required resources are available locally .It also checks the applications's website to see if a new version is available , and if so , automatically downloads and launches it .


Where to find Java Web Start in java distribution ?
It is included in the Java runtime environment since Java 5.0. Just try to find it in bin directory of jdk / jre .















How to launch an application using Java Web Start ?

1. From browser :
Just click on a link from a webpage.

2. From desktop icon :
Shortcuts can be created on desktop or start menu . 

3. From Java Application Cache Viewer :
Cache Viewer allows to directly launch an application that has already  been downloaded . 

Launching Cache Viewer :
a. Go to Control Panel -> Java . This will open Java Control Panel window.
























b. On "General" tab , click on the button "View" ( from section "Temporary Internet Files" ).
This will open a new window "Java Cache Viewer " . Now just double click the application to launch.


4. From command prompt :
On command prompt , just type 
javaws jnlp_url 

jnlp_url : url of the jnlp file of the application.

Monday, October 7, 2013

Inter thread communication showing the usage of notifyAll() method.

Lets start with the methods that facilitates Inter Thread Communication in Java . All these methods are present in java.lang.Object class .

wait()
wait() method is used to instruct the current thread to release the object's lock and get suspended until some other thread invokes notify() or notifyAll() method for the same monitor.

notify()
notify() method is used to wake up a thread that is suspended by the wait() method.

notifyAll()
notifyAll() method is used to wake up all the threads that are suspended by wait() method.

Lets come to our topic . notifyAll() method is important when several threads are waiting on one object. For example there is a class that performs a calculation and many readers are waiting to read the computed calculation.

class Calculator extends Thread {
    private int total;
    private boolean isCalcDone;

    @Override
    public void run() {
        synchronized (this) {
            for (int i = 0; i < 10000; i++) {
                total += i;
            }
            isCalcDone = true; // ------------ (3)
            notifyAll();       // ------------ (4)
        }
    }

    public int getTotal() {
        return total;
    }

    public boolean isCalcDone() {
        return isCalcDone;
    }
}

class CalcReader extends Thread {
    Calculator calculator;

    public CalcReader(Calculator calculator) {
        this.calculator = calculator;
    }

    @Override
    public void run() {
        synchronized (calculator) {
            //Reader threads waits for the Calculator to complete its calculation by calling wait().
            while (!calculator.isCalcDone()) {  // ------------ (1) 
                System.out.println("Waiting for calculator");
                try {
                    calculator.wait();          // ------------ (2)
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("Total is :" + calculator.getTotal());
        }
    }

}

public class NotifyAllExample {
    public static void main(String[] args) {
        Calculator calculator = new Calculator();
        new CalcReader(calculator).start();
        new CalcReader(calculator).start();
        new CalcReader(calculator).start();
        calculator.start();
    }
}

In the above example :
1. We have created three CalcReader threads sharing a common Calculator instance.
2. At (1) , Threads checks if Calculator has completed the  calculation , if not , calls wait() at (2) , releases the lock and waits for the Calculator to complete its calculation.
3. When Calculator completes its calculation , sets isCalcDone to true at (3) and notifies all the waiting threads at (4). 

Saturday, October 5, 2013

Sending POST request using http components HttpClient


Hi . In my previous posts , we talked about the basics of HttpClient ( Click here ) and how to use it safely in a multithreaded environment ( Click here )  . In this post we will learn how we can send POST request to a server using HttpClient . 




Get Ready :
Download HttpClient dependencies and put them in the classpath of your application or if you are a maven user , add dependency in pom :

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3</version>
</dependency>

Lets take an example of form submission . HttpClient provides an entity class named UrlEncodedFormEntity  to encode the form parameters that needs to be send as a part of POST request. 
List<NameValuePair> formData = new ArrayList<NameValuePair>();
formData.add(new BasicNameValuePair("param1", "value1"));
formData.add(new BasicNameValuePair("param2", "value2"));

// Creating UrlEncodedFormEntity that will use the URL encoding to encode form parameters 
// in a form like param1=value1&param2=value2
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formData , Consts.UTF_8);

HttpPost httpPost= new HttpPost("Some URI");

httpPost.setEntity(entity);


Example :
This example below demonstrate the use of  HttpClient to make a POST request .
package in.tutorialhub.httpclient;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

public class PostExample {
 public static void main(String[] args) throws Exception {
  // Creating an instance of HttpClient.
  CloseableHttpClient httpclient = HttpClients.createDefault();
  try {

   // Creating an instance of HttpPost.
   HttpPost httpost = new HttpPost("http://SomeRandomURI");

   // Adding all form parameters in a List of type NameValuePair

   List<NameValuePair> nvps = new ArrayList<NameValuePair>();
   nvps.add(new BasicNameValuePair("param1", "value1"));
   nvps.add(new BasicNameValuePair("param2", "value2"));

   /**
    * UrlEncodedFormEntity encodes form parameters and produce an
    * output like param1=value1&param2=value2
    */
   httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

   // Executing the request.
   CloseableHttpResponse response = httpclient.execute(httpost);
   System.out.println("Response Status line :" + response.getStatusLine());
   try {
    // Do the needful with entity.
    HttpEntity entity = response.getEntity();
   } finally {
    // Closing the response
    response.close();
   }
  } finally {
   httpclient.close();
  }
 }
}

Saturday, September 21, 2013

Intrinsic Locks and Synchronization

What is Synchronization ?
Synchronization is a way to control the access to a shared resource in multithreaded environment in such a way that only one thread can access a shared resource at a time. Synchronization is achieved through the concept of monitor. A monitor is an exclusive lock that is obtained on an object by a thread when a synchronized method is called on the object ( or a synchronized block is executed ). 


Intrinsic lock / Monitor lock.
Intrinsic lock or monitor lock plays an important role in different aspects of synchronization :
  • It enforces exclusive access to object's state .
  • It establishes Happens-before relationship that is essential for visibility .

Syntax.
synchronized keyword is used to denote that a particular block of code is to be executed in a monitor. Synchronization can be done in two ways :

1. Synchronized methods .
synchronized keyword can be used with both instance methods and static methods .
// Synchronizing instance methods . Lock will be taken on the current object i.e object used to call the method doStuff().
public synchronized void doStuff(){
    // Statements to be executed in monitor.
}

// Synchronizing static methods . Lock will be taken on class instance ( java.lang.Class ) 
public static synchronized void doSomeExtra(){
    // Statements to be executed in monitor.
}


2. Synchronized statements.

It is useful for improving concurrency with fine grained synchronization.

// Synchronizing blocks . Lock will be taken on the current object i.e object used to call the method doStuff().
public void doStuff(){
    // Statements that are not executed in monitor.
    synchronized(this){
    // Statements to be executed in monitor.
    }
}

Reentrant synchronization 
Allowing a thread to acquire a lock more than once is called Reentrant synchronization. This can happen in a scenario where one synchronized code , directly or indirectly invokes a method that also contains synchronized code , and both the code use the same lock . Without reentrant synchronization , synchronized code would have to take many additional precautions to avoid having a thread cause itself to block . 

Limitations of Synchronization 
Synchronization can only make sure that a shared object can be accessed by one thread at a time . It can not determine order of the usage . Sometimes there is a need to use a common resource in a specific order by multiple threads .

Race condition in Concurrency

The situation where multiple threads try to operate on a shared resource without proper synchronization  and sequence of their operations interleave is  Race Condition ( Also see Thread interference and Memory consistency errors) .

Example 1 .
The most basic example to describe a Race condition is a Counter class  that increments value of an instance variable . 
class Counter {  
    private int c = 0;  
  
    public void increment() {  
        c++;  
    }  
}
Note :
It seems that the increment operation is atomic ( Atomic operations can't be interleaved by threads ) but it is not . It can further be divided into three steps : 
1. Read the value c. 
2. Increment the value . 
3. Write the incremented value.


Lets imagine that two threads A and B increments the value of instance variable c . Ideally if there is no interleaving of thread's operations , the value of the variable should be 2 as both the threads increment it by 1 . Lets see one of the possible scenario where thread's operations interleave 

Thread A : Read  c ( which is 0 ).
Thread B : Read  c ( Still 0 ).
Thread A : Increments the value by 1.
Thread A : Write the value ( Now c is 1 )
Threab B : Increments the value  
Thread B : Write the value ( Still c is 1 ) 

Here we can see that due to interleaving of Read operations of two threads , the final value of the variable c is 1 and not 2. 

Example 2 .
Below is a short snippet from a singleton class . Here first the code checks whether the instance is null and then creates a new object . The purpose of this code is to ensure that there is only one instance of MySingleton class. 
public MySingleton getInstance(){
   if (instance == null){
       instance  = new MySingleton();
   }
}
Now lets consider that there are two threads trying to get an instance of MySingleton class by calling the method getInstance() . It might be possible , due to interleaving of thread's operations , that both the thread sees the value of instance as null  and in that case , two objects will get created by the threads . 

How to fix the problem ?
Race conditions can be avoided by proper synchronization of the code . As an application developer , you have to enforce locking to make sure that only one thread enters a critical section at a time  and the result of the  thread is visible to others once it  comes out of the synchronized block .


Saturday, September 14, 2013

OOP concept in Java


Hi Guys !!! So this blog is all about the Object Oriented Programming  concepts . Lets start from the very basic concept of Object and Class .

What is an Object ?
Well It is the most basic concept and a key to understand the Object-Oriented programming . Object is an entity that has two characteristics ,  State and Behavior . Some examples of real world object can be : Bike , Chair , Dog etc. 

Lets take an example of a Bike . Bike has some state ( current gear , current speed ) and behavior ( change gear , apply brake ) . One way to begin thinking in an object-oriented way is to identify the state and behavior of real world objects .

Software objects are also similar to the real world objects. They too contains State and Behavior . An Object stores its state in  fields and exposes the behavior through methods.



What is Class ?
Class is a blueprint from which objects of same type can be created . Lets take an example of a Bike again . There are thousands of  bikes with the same characteristics i.e having same make and model . They are created from the same prototype / blueprint called class.


 Now we know the basics of an Object and  Class , so lets move on to Object Oriented principles
  • Inheritance 
  • Polymorphism
  • Abstraction 
  • Encapsulation


1. Inheritance :
Inheritance is the capability of one class to acquire the common state and behavior of   another class while adding its own functionality . In Object Oriented programming  , the concept of inheritance provides the idea of re-usability .  This means we can add additional features to a class without modifying it. 

How to achieve Inheritance in Java ?
extends keyword is used to inherit features of a class . 
class Parent {
// Parent has some state and behavior
}

class Child extends Parent {
// Inherit the common state and behavior of Parent class.
// Provide additional functionality.
}


2. Polymorphism :
Polymorphism means ability of one type to take more than one form . This can also be applied in Java where in sub-classes of a class can define their own unique behaviors and yet share some of the common functionalites of the parent class.

Example : 
Lets take an example of Bike . A company can produce different kind of bikes say , a mountain bike , and a roadbike . Now the two different types of bikes inherit the common features of a bike but also define their own separate features.

How to achieve Polymorphism in Java ? 
Overloading  and Overriding are the two ways to achieve Polymorphism.


3. Abstraction :
Abstraction is an essential element of Object Oriented programming . It refers to the act of presenting essential features without including the background details or explanations.

We can say that abstraction is purposeful suppression , hiding of some details of a process or artifact , in order to bring out more clearly other aspects , details or structures. Abstraction can be of control ( abstraction of actions ) or data . 

How to achieve Abstraction in Java ? 
Abstract classes and Interfaces are used to achieve Abstraction in Java.


4. Encapsulation :
Encapsulation is the binding of data and its associated functions in a single unit called Class . Access to the code and data inside the wrapper is tightly controlled through a well defined interface. Encapsulation provides a protective barrier that prevents the access of code and data from outside the class. 

The main benefit of encapsulation is the ability to re-factor the implemented code without breaking the code of others and thus provides flexibility and maintainability .




Wednesday, September 11, 2013

Using HttpClient safely in a Multi-threaded environment.

In my previous post ( Understanding commons HttpClient with example.) , we discussed about the basics of HttpClient with an example . In this post we will learn how we can use HttpClient in a multi-threaded environment.

Why use HttpClient in Multi-threaded environment ?
Now that's a good question . Suppose we need to download multiple files simultaneously .For example  in my project , we have 18 nodes on live environment . Sometimes we need to download log files from all the nodes for doing some log analysis . Now there are various options to do that . 

  • The first approach is that we can download all the files one by one . Do you think that's a good approach ? I think I know your answer :)
  • The second approach is we can use HttpClient with multiple threads to download all the log files concurrently . 


So what is the problem now ?
For execution , each method requires an instance of  HttpConnection.  HttpConnection can only be safely used from a single thread and method at a time . Also connections are finite resources and they should be managed in a proper way . We need  to make sure that they are properly allocated to the methods that require them . 

OK Cool . But how are we going to do that ?
MultiThreadedHttpConnectionManager to the rescue .

Below code snippet shows how we can use it with HttpClient.
MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
HttpClient client = new HttpClient(connectionManager); 


Example : 
In this example , there are three separate threads making a GET request to three different URIs . For convenience , I have taken the URIs in an array .
  • Here instead of creating only HttpClient instance ( as in the previous blog ) , first an instance of MultiThreadedHttpConnectionManager   is created and then its reference is passed to the HttpClient in constructor.
  • Connection is released manually in the finally block .This is because HttpClient doesn't know when a method is not using a connection as method's response is not read directly by the HttpClient. The response is read using method's connection , so a connection can not be released until the response body is read which is after the HttpClient finishes executing the method. 
package httpclient;

import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.StatusLine;
import org.apache.commons.httpclient.methods.GetMethod;

public class MultiThreadedExample {

    public static void main(String[] args) {

        // Creating MultiThreadedHttpConnectionManager
        MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();

        // Passing it to the HttpClient.
        HttpClient httpClient = new HttpClient(connectionManager);

        // URIs that needs to be GET by threads.
        String[] urisToGet = { "https://www.google.com/search?hl=en&q=httpclient&btnG=Google+Search",
                "https://www.google.com/search?hl=en&q=servicemix&btnG=Google+Search",
                "https://www.google.com/search?hl=en&q=tomcat&btnG=Google+Search", };

        // create a thread for each URI
        for (int i = 0; i < urisToGet.length; i++) {
            GetMethod get = new GetMethod(urisToGet[i]);
            new CreateThread(httpClient, get, "Thread-" + i).start();
        }
    }

    static class CreateThread extends Thread {
        private final HttpClient httpClient;
        private final GetMethod method;

        public CreateThread(HttpClient httpClient, GetMethod method, String name) {
            super(name);
            this.httpClient = httpClient;
            this.method = method;
        }

        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName() + " - about to get something from "
                        + method.getURI());

                // Execute the method.  
                int statusCode = httpClient.executeMethod(method);

                if (statusCode != HttpStatus.SC_OK) {
                    System.err.println("Method failed: " + method.getStatusLine());
                }

                // Reading the status body.  
                StatusLine statusLine = method.getStatusLine();
                System.out.println(Thread.currentThread().getName() + " " + statusLine);
            } catch (HttpException e) {
                System.err.println("Fatal protocol violation: " + e.getMessage());
            } catch (IOException e) {
                System.err.println("Fatal transport error: " + e.getMessage());
            } finally {
                // Release the connection.  
                method.releaseConnection();
            }
        }

    }

}

Monday, September 9, 2013

Understanding commons HttpClient with example.

What is HttpClient :
HttpClient is a client side  HTTP transport library whose purpose is to transmit and receive HTTP messages. The HTTP (Hyper Text Transfer Protocol ) is the most significant protocol used on the internet today. HttpClient can be used by anyone building HTTP-aware client applications such as Web Browsers , Web services clients or any system that uses HTTP protocol for distributed communication. 


HttpClient is not a browser :
Though it seems that HttpClient is simulating the functionality of a web browser , but that's not true . HttpClient is not a browser. HttpClient will not attempt to cache content, execute javascript embedded in HTML pages, try to guess content type, or reformat request / redirect location URIs.


Get Ready :

Download HttpClient dependencies and put them in the classpath of your application

or if you are a maven user , add dependency in pom :

<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.0</version>
</dependency>

Steps to create HttpClient :

1. Create an instance of HttpClient.
2. Create an instance of HttpMethod.
3. Tell HttpClient to execute method.
4. Read the respose.
5. Release connection.
6. Deal with the respone. 


Example : This code demonstrates how HttpClient makes a GET request to Google Server and bring back the results.
public class GoogleSearch {
     private static String searchUrl = "https://www.google.com/search?hl=en&q=httpclient&btnG=Google+Search";

     public static void main(String[] args) {

         // Create an instance of HttpClient.
         HttpClient client = new HttpClient();

         // Create a method instance.
         GetMethod method = new GetMethod(searchUrl);

         // Provide custom retry handler.
         method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler(3, false));

         try {
             // Execute the method.
             int statusCode = client.executeMethod(method);

             if (statusCode != HttpStatus.SC_OK) {
                 System.err.println("Method failed: " + method.getStatusLine());
             }

             // Read the response body.
             String responseBody = method.getResponseBodyAsString();

             // Deal with the response.
             System.out.println(responseBody);

         } catch (HttpException e) {
             System.err.println("Fatal protocol violation: " + e.getMessage());
         } catch (IOException e) {
             System.err.println("Fatal transport error: " + e.getMessage());
         } finally {
             // Release the connection.
             method.releaseConnection();
         }
     }
}

Tuesday, September 3, 2013

Thread interference and Memory consistency errors.

Generally threads communicates by sharing member variables and the Object references members refer to. Well this type of communication is extremely efficient but can cause two kind of problems :

1. Thread Interference 
2. Memory Consistency Errors 

Interference occurs when two operations , running in different threads , but acting on the same data , interleave.

See the Counter class  ( example taken from docs.oracle.com ).

class Counter {
    private int c = 0;

    public void increment() {
        c++;
    }

    public void decrement() {
        c--;
    }

    public int value() {
        return c;
    }

}
Suppose there are two threads Thread-A and Thread-B working on the same counter instance  . Say Thread-A invokes increment() , and at the same time Thread-B invokes decrement() . Thread-A reads the value c and  increment it by 1 . At the same time Thread-B reads the value ( which is 0 because the incremented value is not yet set by Thread-A) , decrements it and set it to -1 . Now Thread-A sets the value to 1 .

Oops what went wrong ? The result of Thread-B is lost. It might be the other case as well or there could be no error at all . This uncertainty makes it difficult to identify bugs .

Memory Consistency Errors occurs when different threads have inconsistent views of the shared data. 

In the above class counter , Lets say there are two threads working on the same counter instance ,  calls the increment method to increase the counter's value by 1 . Here it is no guarantee that the changes made by one thread is visible to the other .

Avoiding Memory Consistency Errors
This can be avoided by establishing a happens-before relationship . This relationship guarantees that memory write by one thread is visible to a read by other thread if the write operation happens-before the read operation. There are various actions that can form a happens-before relationship.

  • Synchronization
  • volatile keyword
  • Thread.start()
  • Thread.join()


Thursday, August 15, 2013

Understanding Threads in Java

A Thread is an independent sequential path of execution within a process / program. Multiple threads can run concurrently in a program . Threads are lightweight as compared to the process as at runtime , they exist in a common memory space and can share process's resources like  data and code.

Threads make the runtime environment asynchronous , allowing different tasks to be performed concurrently . In Java , a thread is represented and controlled by an object of class java.lang.Thread.

main() method is executed as a Thread.
When an application ( or a program ) is run, a user thread is created to execute the main() method of the application. This thread is called main thread.

Thread Creation :
A thread in java is represented by an object of class java.lang.Thread and can be created in two ways :

1. Implementing java.lang.Runnable interface.
The Runnable interface defines a method run() that contains the code that is to be executed in a thread. Lets create a thread that says " Hello User ".

public class MyRunnable implements Runnable {

 // Statements defined in run() methods are executed as a thread.
 public void run(){
  System.out.println("Hello User");
 }

 public static void main(String[] args) {             
  // Creating an object of Thread class and passing a Runnable in its constructor.
  Thread thread = new Thread(new MyRunnable());

  // Starting a thread.
  thread.start();
 }
}
 
    
2. Extending java.lang.Thread class.
Another way to create a thread is by extending Thread class  and override the run() method .The Thread class itself implements Runnable but its run() method does nothing.

public class MyThread extends Thread {

 public void run() {
  System.out.println("Hello User");
 }

 public static void main(String[] args) {
  new MyThread().start();
 }
}

What is Multitasking ?

Multitasking is the ability to perform more than one activity concurrently on a computer. We can further break multitasking into process based and thread based .

Process-based Multitasking 
Process-based multitasking allows processes ( or programs ) to run concurrently on a computer. For example , running different applications at the same time like downloading a file and printing a file .

A process has a self-contained execution environment. A process has a complete , private set of basic resources . Each process has its own memory space.

Thread-based Multitasking
Thread-based multitasking allows different parts of the same process ( program ) to run concurrently .
A good example is printing and formatting text in a word processor at the same time.
Thread-based multitasking is only feasible if the two parts are independent of each other or more precisely they are independent paths of execution at run time.

Threads are also referred as lightweight processes and they also provide an execution environment . Threads exists within a processes and share its resources like memory and open files.

We have several advantages of Thread-based multitasking over Process-based multitasking .

1. Threads shares the same address space.

2. Context switching between the threads is less expensive than in Processes.



Sunday, June 16, 2013

Tomcat throwing Java.Lang.OutOfMemoryError: PermGen Space

Your Tomcat might have thrown such kind of exception while running : 


java.lang.OutOfMemoryError: PermGen space
Java heap is structured into regions called generations. The permanent generation is the area of the heap where class and method objects are stored. 
If an application loads a very large number of classes, then the permanent generation can get out of space.In that case , we  might need  increase the perm gen size in Tomcat using the files catalina.bat or catalina.sh .

Assign the following values to JAVA_OPTS and add this in catalina.bat or catalina.sh file.


JAVA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8 -server -Xms1536m 
-Xmx1536m -XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m 
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"
Snippet from catalina.sh file





Sunday, April 21, 2013

Install MongoDB as windows service

We can also configure MongoDB to run as a windows service .  
mongod.exe added support for running as a Windows service in version 2.0, and mongos.exe added support for running as a Windows Service in version 2.1.1.

Step 1 : Create configuration file mongod.cfg .

echo logpath=C:\mongodb\log\mongo.log > C:\mongodb\mongod.cfg

A new file mongod.cfg will be created at location C:\mongodb. This file contains an entry logpath which tells mongodb to save all logging information in the specified file mongo.log


Step 2 :  Install MongoDB as a service .
Execute following command in command prompt :

mongod --config C:\mongodb\mongod.cfg --install



A new windows service will be created .


Step 3 : Start Mongo Service 
Execute following command in command prompt :

net start MongoDB




Other Options :

1 . Stopping MongoDB Service :
     net stop MongoDB


2 . Removing MongoDb service :
     mongod.exe --remove





Thursday, April 18, 2013

How to delete a tag in Github.

Following commands can be used to delete a tag in git.

1. Delete tag from local
     git tag -d [tag];

2. Push changes to remote
     git push origin :[tag]

Example :
    
Let say you have created a tag by name v6.37.1 . Now to delete the tag from git :

1.  git tag -d v6.37.1

2.  git push origin :v6.37.1

NOTE :
If your tag has the same name as one of your branches then ,

1. git tag -d [tag]

2. git push origin :refs/tags/[tag]

MongoDB installation on Windows

1. Download MongoDB .

2. Extract the downloaded zip to a directory say, 

 C:\mongodb-win32-x86_64-2.4.2
3. set path  ( C:\mongodb-win32-x86_64-2.4.2\bin ) in environment variable ( Optional )
4. Mongo requires a data directory to store its files . Default location is  C:\data\db.  Create these  folders.
5. Start MongoDB in command prompt. mongod.exe is present in the bin directory of the distribution.



6.Connect to MongoDb using  Mongo shell in a new command prompt.


Now you can insert data in mongo db . Below is an example .



Wednesday, April 17, 2013

How to configure/integrate Weblogic8.1 in MyEclipse 5.5.1 GA

Integrating weblogic in MyEclipse is quite easy but before beginning you should be familiar with Weblogic
Server concepts and installation location details.


Properties :-


1)BEA Home Directory Path to BEA home directory. WebLogic consults this directory for its license and registry files. eg. C:\bea (considering that weblogic is installed in C:\ directory)

2)Weblogic installation directory Path to WebLogic Server installation directory. (eg. C:\bea\weblogic81)


3)Administration Username The name of the WebLogic system admin user.


4)AdministrationPassword The password of the WebLogic system admin user.


5)Execution Domain Root Directory that contains the execution domain directory.( eg. C:\bea\user_projects\mydomain)


6)Execution Domain Name The name of the WebLogic domain to execute under the root directory.( e.g. mydomain)


7)Execution Server Name The name of the WebLogic server that runs the domain. The server name is specified within the domain’s config.xml file. (eg. myserver)


8)Hostname:Number The hostname: portnumber of WebLogic server instance.(eg. localhost:7001)


9)Security Policy File The location of the security file used by WebLogic(eg. C:\bea\weblogic81\server\lib\weblogic.policy)


10)JAAS Login Configuration File This is not compulsary parameter It is required when the login configuration path is not specified in the security policy file or the user’s home directory for WLS 6.x.



Steps to integrate webogic8.1 :-1. Begin by clicking on the icon in the MyEclipse toolbar for configuring servers


2. Select the option "configure server"


3. select Application Servers -> Weblogic -> Weblogic 8.x

4. Fill all the required parameters as specified below. The parameters in this example are filled by considering that the weblogic server is installed in C:\ directory i.e the BEA Home directory is C:\bea





Steps to Configure JDK properties:-
The picture below defines the Java JDK preferences for an application server connector. The connector will use these parameters to determine the Java Virtual Machine and commandline arguments in the launch phase of an application server connector's life-cycle.


NOTE: The JDK Name value must identify a full Java JDK install. Do not specify a JRE. Doing so will result in launch failures of your server connector.



Steps to configure Launch properties:-Launch Mode defines if the mode in which the server connector will launch an instance. Debug mode enables uses of Eclipse/MyEclipse Java and JSP debugging capabilities such as breakpoints, inspectors, and hot-swap code changes. Run mode disables use of debugging features but offers better performance.



Steps for Configuring Paths:-There are three parameters to be provided and none of them is compulsary so you can leave them blank.

a)Prepend to classpath:-
Browse to and select the JAR and ZIP archives and the class directories you wish to have added to the beginning of the server connector JVM's classpath. Additions will be loaded by the Java VM before the web-server core classes.

b)Append to classpath:-
Browse to and select the JAR and ZIP archives and the class directories you wish to have added to the end of the server connector JVM's classpath. Additions will be loaded by the Java VM after the web-server core classes.

c)Append to library path:-
Browse to and select the platform-specific native libraries to be appended to the java.library.path.


So all the required configuration is done. Now just start the server and deploy your projects.

Done !!!

How to insert an image in Oracle through Servlet


Hi all,

In this post i will tell you how to insert image in a database (Oracle) through a Servlet.

First of all make a table in Oracle named "image_master" having three fields i.e id, name, image.

Step 1:- Creating table in database.
just copy / paste the code in oracle SQL command line:-
CREATE TABLE  "IMAGE_MASTER" 
   ( "ID" NUMBER NOT NULL ENABLE, 
 "NAME" VARCHAR2(40), 
 "IMAGE" BLOB, 
  CONSTRAINT "IMAGE_MASTER_PK" PRIMARY KEY ("ID") ENABLE
   )

Step 2:- Create a Servlet for inserting image.
Now after creating the table, make a servlet named "InsertImage" which extends HttpServlet and overrides doGet() and doPost() method.

package others;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class InsertImage extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            /**
             * make a database connection. Here we are making connection with oracle database.
             * for Oracle Type-4 driver:-
             * Driver Class = ("oracle.jdbc.driver.OracleDriver")
             * Connection String = ("jdbc:oracle:thin:@localhost:1521:xe","user_name","password")
             */
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "oralce");
            /**
             * making an object of FileInputStream for reading the image file in form of bytes.
             * path of the file is provided as an argument.
             */
            FileInputStream fis = new FileInputStream("c:/images/hello.jpg");
            PreparedStatement st = con.prepareStatement("insert into image_master values(?,?,?)");
            st.setInt(1, 1001);
            st.setString(2, "Prakash");
            /**
             * method setBinaryStream() is used for inserting image in database.
             */
            st.setBinaryStream(3, fis, fis.available());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

Step 3:- Making web.xml entry:-
imageServlet 
servlets/ImageServlet

MongoDB introduction

MongoDB is a Non Relational JSON document store/database . Non relational means it does not supports relational algebra between the tables like SQL ( Does not support JOINs).

Benefits :

  • High performance.
  • High availability.
  • Highly  scalable.


MongoDB does not supports JOINs :
Joins scales poorly when we try to scale out to multiple nodes. 

No transaction support :
MongoDB doesn't provide any transaction support. Something that requires multiple updates within a relational system can be handled within a single atomic transaction within a single document in mongo.

Sunday, February 17, 2013

Dependency Injection ( DI )

Dependency Injection means inversion of responsibilities with regard to how an object obtains references to collaborating objects.

When applying DI , objects are given their dependencies at creation time by some external entity that coordinates with each object in the system.

Benefits : Loose coupling.

Friday, February 15, 2013

Define DDL , DML , TCL

Data Definition Language ( DDL ) :
Data Definition Language are used to define the structure of a database or schema.
Some of the example includes statements like CREATE , ALTER , DROP etc.
Oracle Database implicitly commits the current transaction before and after every DDL statement.

Examples :
  • CREATE - can be used to create a database , table , stored procedure.
  • ALTER - can be used to alter the structure of databse table like add a new column.
  • DROP - can be used to drop objects from database like drop a table.
  • TRUNCATE - remove all records from a table . also remove all spaces allocated for the recods.
  • COMMENT - can be used to add comments to data dictionary.
  • RENAME - renames an object

            Data Manipulation Language ( DML ) :
            Data Manipulation Language can be used to modify / alter the data of existing schema objects. 
            DML statements do not implicitly commit the current transactions.

            Example :
            • SELECT - used to retrive data from a database table.
            • INSERT - used to insert new record in a table.
            • UPDATE - can be used to update column values of a table.
            • DELETE - can be used to delete records from a table.
            • MERGE - insert or update operation.
            • EXPLAIN PLAN - explain access path to data.
            • CALL - can be used to call PL/SQL.
            • LOCK TABLE - controls the concurrency.

            Transaction Control Statements ( TCL ) :
            Transaction Control Statements are used to control the manipulations made by Data Manipulation Language ( DML ) statements . 

            Example :
            • COMMIT - used to commit the transaction so that any changes made by the query are reflected by the database table.
            • ROLLBACK - revert the changes that were made in the last commit.
            • SAVEPOINT -  creates / identifies a point in the transaction to which you can rollback later.
            • SET TRANSACTION - change transaction options like isolation level.

            Session Control Statements  :
            Session control statements dynamically manage the properties of a user session. These statements do not implicitly commit the current transaction.

            Example :
            • ALTER SESSION
            • SET ROLE