Thursday, April 26, 2012

Get Sub List of Java ArrayList Example

package com.subList.demo;

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

/**
 * This Java Example shows how to get sub list of java ArrayList using subList method.
 *
 * @author abdul
 */
public class SubListDemo {

    public static void main(String args[]) {

        //create an ArrayList object
        List<String> list = new ArrayList<String>();
        int range = 4;

        //Add elements to Arraylist
        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");
        list.add("E");
        list.add("F");
        list.add("G");
        list.add("H");
        list.add("I");
        list.add("J");
        list.add("K");
        list.add("L");
        list.add("M");
        list.add("N");
        list.add("O");
        display("Displaying all elements of the list : ", list);

        if(list.size() > range) {
            int from = 0;
            int to = range;
            List<String> lt = null;
            do {
                //Check whether "to" value never exceeds from the list size
                //otherwise it would throw error while fetching subList
                if(list.size() - from > range ) {

                    // To get a sub list of Java ArrayList use List subList(int startIndex, int endIndex) method.
                    //This method returns an object of type List containing elements from startIndex to endIndex - 1
                    lt = list.subList(from, to);

                    display("SubList from " + from + " to " + to, lt);
                } else {
                    lt = list.subList(from, list.size());
                    display("SubList from " + from + " to " + list.size(),lt);
                }
                from += range;
                to += range;
            }while(from < list.size());
        } else {
            display("Displaying all elements of the list : " , list);
        }
    }

    /**
     * Display elements of sub list.
     * @param message
     * @param list sublist of the list to print
     */
    private static void display(String message,List<String> list) {
        System.out.println(message + "\nList: " + list);
    }
}

Output:
Displaying all elements of the list :
List: [A, B, C, D, E, F, G, H, I, J, K, L, M, N, O]
SubList from 0 to 4
List: [A, B, C, D]
SubList from 4 to 8
List: [E, F, G, H]
SubList from 8 to 12
List: [I, J, K, L]
SubList from 12 to 15
List: [M, N, O]


Related link:
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/List.html

Wednesday, April 25, 2012

Debug Java applications remotely with Eclipse



Remote debugging is a way of debugging any process running on some other location from your development machine. Local debugging is the best way in my opinion and should always be preferred over remote debugging but if local debugging is not possible and there is no way to debug your process then remote debugging is the solution.


Many of us work on a project which runs on Linux operating system and we do development mostly on Windows.
Eclipse provides us most useful feature called "Remote debugging" by using which you can debug your Linux running process from your windows machine.

Now let's see how we can setup remote debugging in Eclipse:

Just take a example of a simple program that we want to be debugged:


package com.tutoial.debugger;

/**
 * @author abdul
 *
 */
public class Debug {
    public static void main(String args[]) {
        for(int i=1; i<=10;i++) {
            System.out.println("2 * "+ i + " = " + 2*i);
        }
    }
}


Convert it into the jar.
From Eclipse , You can do it by following step:
1. Select the file that you want to export, Right click and choose "export".
2 .Goto Java-> jar and click Next
3. Browse the path where you want to export and click "finish".





Now, In order to remote debug a java application, Start your application with the following JVM debug options:

java -Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y suspend=y -jar debug.jar


This will start java applicaiton debug.jar into debug mode using Java Debug Wire Protocol (jdwp) protocol and it will listen on port 8000 ,suspend=y will ensure that that application will not start running until eclipse connect it on speicified debug port.

After running it you should see something like that:
          Listening for transport dt_socket at address: 8000


Go to Eclipse and open debug dialog (you can press Alt+R, B). Create a new Remote Java Application Configuration. Select connection type as "Socket attach" and specify Connection Properties (for our example host would be localhost, and port would be 8000).




It also important to note that application must be start before eclipse tries to connect it other wise Eclipse will throw error "Failed to connect to remote VM. Connection refused" or "Connection refused: connect"

Enjoy..!!!!


Related link:

http://help.eclipse.org/helios/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Ftasks%2Ftask-remotejava_launch_config.htm
http://www.ibm.com/developerworks/java/library/os-eclipse-javadebug/index.html?ca=dgr-jw22os-eclipse-javadebug/index.html&S_TACT=105AGX59&S_CMP=GRsitejw22

Wednesday, March 21, 2012

How to install springsource tool suite on linux

Download the STS self-extracting shell script (*.sh) that matches your OS and machine architecture from the following Url:





http://www.springsource.org/eclipse-downloads


Please make sure to download and install STS versions that match your JDK installation.

Once downloaded, launch the installation by running the following command in a terminal session:
$ sh springsource-tool-suite-2.9.0.RELEASE-e3.7.2-linux-gtk-installer.sh

Follow the on-screen instructions to finish the installation. See “Running the STS Installer”.

Tuesday, March 20, 2012

How to find MYSQl Port No and Version ?


mysql> show variables like 'port';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| port          | 3306  |
+---------------+-------+
1 row in set (0.02 sec)

mysql> show variables like 'version';
+---------------+-------------------+
| Variable_name | Value             |
+---------------+-------------------+
| version       | 5.0.45-community-nt |
+---------------+-------------------+
1 row in set (0.00 sec) 

Monday, March 12, 2012

Java JVM Shutdown Hook - tutorial

JVM shutdown hooks provide a clean and simple mechanism for registering application-specific behavior that performs the required cleanup work when a JVM terminates.

It is a Java feature that let you have a piece of Java code run whenever the JVM terminates under one of the following conditions:

  - The program exits normally, such as when the last non-daemon thread exits or when the                         Runtime.exit() method is invoked.

  -  The virtual machine is terminated in response to a user interrupt, such as typing CTRL-C, or a                      system-wide event, such as user logoff or system shutdown (for example, the JVM receives               one of  the interrupt signals SIGHUP (Unix Only), SIGINT, or SIGTERM).

A shutdown hook is a Java class that extends java.lang.Thread and is get registered with the Runtime.addShutdownHook()method. Your application may install multiple shutdown hooks. On JVM termination, each shutdown hook will be started and will run concurrently, so the normal rules of thread synchronization apply. You can write shutdown hooks to do anything that a normal thread would do; the JVM will treat them like any other.

Generally we write a shutdown hook to do any last-minute tidying, such as flushing memory buffers, closing files, or displaying an exit message. The JVM will always wait until all shutdown hooks have completed before continuing with the rest of the shutdown sequence, so it is important that your shutdown hooks do actually complete.

The following example shows how to write and install a Java shutdown hook.

/**
 * Implementation of JVM shutdown hook
 *
 * @author abdul
 *
 */
public class ShutDownHook {
    public static void main(String args[]) {
        ShutDownHook hook = new ShutDownHook();
        System.out.println( "Running Main Application..." );
        // Java code to register shutdown hook:
        hook.attachShutDownHook();
        // You can unregister the shutdon hook too.
        hook.removeShutdownHook();
        System.out.println("Exit");
    }

    Thread shutdown =new Thread() {
        @Override
        public void run() {
            //Do your cleaning stuff here eg closing connection,Saving some logs etc
            System.out.println("Inside Add Shutdown Hook");
        }
    };

    private void attachShutDownHook() {
        Runtime.getRuntime().addShutdownHook(shutdown);
        System.out.println("Shut Down Hook Attached.");
    }

    public void removeShutdownHook(){
        Runtime.getRuntime().removeShutdownHook(shutdown);
    }
}

 


There is also a method named removeShutdownHook, which also takes the reference to the Thread object as a parameter. This method allows you to remove a Thread from the list of threads to be started by the VM before it closes (Runtime.getRuntime().removeShutdownHook(shutdown); for the above shutdown hook example).

FAQ On JVM Shutdown Hook API

Thursday, March 8, 2012

Java HashMap Example

The HashMap class uses a hash table to implement the Map interface. This allows the execution time of basic operations, such as get() and put(), to remain constant even for large sets.

The following constructors are defined:  
HashMap( )
HashMap(Map m)
HashMap(int capacity)
HashMap(int capacity, float fillRatio)

 

Hash map does not guarantee the order of its elements. Therefore, the order in which elements are added to a hash map is not necessarily the order in which they are read.

Here is the code:
 
import java.util.HashMap;
import java.util.Map;

/**
 *
 * This Java HashMap example describes the basic operations performed on the HashMap
 * @author abdul
 *
 */
public class HashMapExample {
    public static void main(String args[]){
       
        // constructs a new empty HashMap with default initial capacity       
        Map<Integer,String> hashMap = new HashMap<Integer,String>();
      
        // adding value into HashMap
        hashMap.put(new Integer(1),"DELL");
        hashMap.put(new Integer(2),"SONY");
        hashMap.put(new Integer(3),"LENOVO");
        hashMap.put(new Integer(4),"SAMSUNG");
        hashMap.put(new Integer(5),"HP");
    
        //To get the size of HashMap       
        System.out.println("HashMap Size: " + hashMap.size());
     
        // To Find particular value from the HashMap:
        if(hashMap.containsValue("HP")){
            System.out.println("HashMap contains HP");
        }else{
            System.out.println("HashMap does not contain HP");
        }
      
        //To find particular key in HashMap
        if( hashMap.containsKey(new Integer(2)) ){
            System.out.println("HashMap contains key");
        }else{
            System.out.println("HashMap does not contain key");
        }
      
        /*
        Use get method of HashMap to get value mapped to particular key.       
        Signature of the get method is,       
        Object get(Object key)       
        */
      
        String value = hashMap.get(new Integer(5));       
        System.out.println("Value : " + value);

        //To get the key value pair of hashMap
        for (Map.Entry<Integer, String> entry1 : hashMap.entrySet()) {
            Integer key = entry1.getKey();
            String data = entry1.getValue();
            System.out.println("key value : " + key + "\t" + data );

        }
 
        // To remove something from the hashmap      
        System.out.println( hashMap.remove(new Integer(4)) + " removed from the hashMap");
       
        //Display value of HashMap
        System.out.println("HashMap : " + hashMap );
    }
}

Output:
HashMap Size: 5
HashMap contains HP
HashMap contains key
Value : HP
key value : 1    DELL
key value : 2    SONY
key value : 3    LENOVO
key value : 4    SAMSUNG
key value : 5    HP
SAMSUNG removed from the hashMap
HashMap : {1=DELL, 2=SONY, 3=LENOVO, 5=HP}

How to get free disk space of a drive in java ?

JDK 1.6 provides few new methods  getTotalSpace(),getFreeSpace(), bundled with java.io.File. These methods provides essential information regarding disk space.

getFreeSpace() method-   Returns the number of unallocated bytes in the partition named by this abstract path name.
getTotalSpace() method - Returns the size of the partition named by this abstract pathname.


Here is the code: 

import java.io.File;

/**
 * Program that returns the number of unallocated bytes , total space in the partition.
 *
 * @author abdul
 *
 */
public class DiskDetail {
    public static void main(String[] args) {
        File file = new File("C:");
        long totalSpace = file.getTotalSpace(); // total disk space in bytes.
        long freeSpace = file.getFreeSpace(); // unallocated / free disk space
        long  diskUsage = (totalSpace - freeSpace);
       
        System.out.println("Total size : " + totalSpace + " bytes");
        System.out.println("Space free : " + freeSpace + " bytes");
        System.out.println("Used Space : " + diskUsage + "bytes");
    }
}

Output:
Total size : 107373129728 bytes
Space free : 44510306304 bytes
Used Space : 62862823424bytes

Reference: 

http://docs.oracle.com/javase/6/docs/api/java/io/File.html 


 

How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...