Search This Blog

Thursday, 19 January 2012

Some Utility Methods

/**************** Stack Trace as  string ****************/

/**
* Returns the string version of a {@link Throwable}
* @param e An instance of {@link Throwable}
* @return String
*/
public static String stackTraceToString(Throwable e) {
   StringWriter stringWritter = new StringWriter();
            PrintWriter printWritter = new PrintWriter(stringWritter, true);
            e.printStackTrace(printWritter);
            printWritter.flush();
            stringWritter.flush();
            return stringWritter.toString();
}

Tuesday, 17 January 2012

DEFENDING Singleton pattern against reflection through security policy file

This will  be demonstrated through DEFENDING Singleton pattern against reflection even singleton class have private constructor.

First we have to set some VM args to define, policy file path and enable security manager.These are as below:
  • -Djava.security.manager
  • -Djava.security.policy=<file path>/.java.policy
/******* Singleton Class *******/

package com;

import java.lang.reflect.Constructor;

public class SingletonClass {

private static SingletonClass singletonObject;
static {

}

/** A private Constructor prevents any other class from instantiating. */
private SingletonClass() {
// Optional Code
}

public static synchronized SingletonClass getSingletonObject() {
if (singletonObject == null) {
singletonObject = new SingletonClass();
}
return singletonObject;
}

public static void main(String args[]) {
try {
Constructor constructor = SingletonClass.class
.getDeclaredConstructor();
constructor.setAccessible(true);
SingletonClass myObject = (SingletonClass) constructor
.newInstance();
SingletonClass myObject2 = SingletonClass.getSingletonObject();
System.out.println(myObject.equals(myObject2));


} catch (Exception e) {
e.printStackTrace();
}
}

public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}

/********* Other class trying to create object of above singleton class through refelection **********/

public class CreateObject {
public static void main(String args[]) {
try {
  Constructor constructor = SubClass.class
.getDeclaredConstructor(Integer.class);
constructor.setAccessible(true);
SubClass myObject = (SubClass) constructor.newInstance(1);
SingletonClass myObject2 = SingletonClass.getSingletonObject();
System.out.println(myObject.equals(myObject2)); 
} catch (Exception e) {
e.printStackTrace();
}
}
}

/******************* Policy file named as .java.policy ***************/
  grant codeBase "file:com/SingletonClass" {
  permission java.lang.reflect.ReflectPermission "com.SingletonClass";
  };

Note: In this policy file we are setting that SingletonClass is only class which can create its object through reflection, NO One else.

/********************* Output when ran CreateObject ***************/

java.security.AccessControlException: access denied (java.lang.reflect.ReflectPermission suppressAccessChecks)
at java.security.AccessControlContext.checkPermission(Unknown Source)
at java.security.AccessController.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkPermission(Unknown Source)
at java.lang.reflect.AccessibleObject.setAccessible(Unknown Source)
at com.Verma.main(CreateObject.java:<line num>)



Thursday, 5 January 2012

Reverse Linked List

/*********** Recursion ***************/


private Node reverseList(Node root) {
if (root.next == null) {
return root;
} else {
Node tail = reverseList(root.next);
root.next.next = root;
root.next = null;
return tail;
}
}



/************* Iteration ***************/

private Node reverseIte(Node head) {
Node remaining = null;
Node previous = null;

while (head != null) {
remaining = head.next;
head.next = previous;
       previous = head;
       head = remaining;
}
return previous;
}


  

Applet - Servlet Communication

/************* Servlet ***************/
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Vector;

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


public class CustomServlet extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
  {
     try
    {
      ObjectOutputStream oos = new ObjectOutputStream(res.getOutputStream());
      ObjectInputStream ois = new ObjectInputStream(req.getInputStream());
    
      if (ois == null)
      {
           return;
      }
      String reqObj = (String) ois.readObject();     
  }
}


/************* Applet *****************/

package connection;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.Verma;

public class ServletCom {
    HttpURLConnection con = null;
    ObjectInputStream ois = null;
    ObjectOutputStream oos = null;
    OutputStream os = null;
    URL url = null;

    // this function create the ois
    private boolean openOIS() {
        try {
            // Stream to write to server
            ois = new ObjectInputStream(con.getInputStream());
            if (ois == null) {
                closeConnection();
                return false;
            }
            return true;
        } catch (Exception e) {
            closeConnection();
            return false;
        }
    }

    // this function create the oos
    private boolean openOOS() {
        try {
            // Stream to write to server
            oos = new ObjectOutputStream(con.getOutputStream());
            if (oos == null) {
                closeConnection();
                return false;
            }
            os = con.getOutputStream();

            if (os == null) {
                closeConnection();
                return false;
            }
            return true;
        } catch (Exception e) {
            closeConnection();
            return false;
        }
    }

    // This function creating connection and initialize all required connection
    // variables
    private boolean createConnection(URL urlCodeBase) {
        try {
            if (con != null) {
                return true;
            }
           
            String argString = ""; // default
            url = new URL(urlCodeBase.toExternalForm() + argString);
            con = (HttpURLConnection) url.openConnection();
            con.setDoOutput(true);
            con.setDoInput(true);

            // Turn off caching
            con.setUseCaches(false);
            con.setDefaultUseCaches(false);

            return true;
        } catch (Exception e) {
            closeConnection();
            return false;
        }
    }

    // this function send the request vector to servlet
    private boolean sndReq(Verma custObj) {

        try {
            oos.reset();
            oos.writeObject(custObj);
            oos.flush();

            return true;
        } catch (Exception e) {
            closeConnection();
            return false;
        }
    }

    // this function send the rcv the response from servlet
    private Object rcvRes() {

        try {
            Object resultObj = ois.readObject();
            if (resultObj instanceof String) {
                return null;
            }

            return resultObj;
        } catch (Exception e) {
            closeConnection();
            return null;
        }
    }

    // This method to connect with servlet each request type will be set in the
    // vector parameter
    public Object startPointToGetData(URL urlCodeBase,
            Verma custObj) {

        Object resultObj = null;

        try {
            if (!(createConnection(urlCodeBase))) {
                return null;
            }

            if (!openOOS())
                return null;

            if (!(sndReq(custObj)))
                return null;

            if (!openOIS())
                return null;
            resultObj = rcvRes();

            closeConnection();

            return resultObj;
        } catch (Exception e) {
            closeConnection();
            return null;
        }
    }

    // To close all the connection with servlet and streams
    public void closeStreams() {
        try {
            if (oos != null) {
                oos.close();
                oos = null;
            }
            if (ois != null) {
                ois.close();
                ois = null;
            }
            if (os != null) {
                os.close();
                os = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // To close all the connection with servlet and streams
    public void closeConnection() {
        try {
            url = null;
            if (con != null) {
                con.disconnect();
                con = null;
            }
            closeStreams();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}






Wednesday, 4 January 2012

Binary Tree Information


Binary search tree: (Copied from Wiki)
A sorted binary tree
Depth-first
  • Preorder traversal sequence: F, B, A, D, C, E, G, I, H (root, left, right)
  • Inorder traversal sequence: A, B, C, D, E, F, G, H, I (left, root, right); note how this produces a sorted sequence
  • Postorder traversal sequence: A, C, E, D, B, H, I, G, F (left, right, root)
Breadth-first
  • Level-order traversal sequence: F, B, G, A, D, I, C, E, H
pre-orderin-orderpost-orderlevel-order
push F
pop F
push G B
pop B
push D A
pop A
pop D
push E C
pop C
pop E
pop G
push I
pop I
push H
pop H
push F B A
pop A
pop B
push D C
pop C
pop D
push E
pop E
pop F
push G
pop G
push I H
pop H
pop I
push F B A
pop A
push D C
pop C
push E
pop E
pop D
pop B
push G I H
pop H
pop I
pop G
pop F
enqueue F
dequeue F
enqueue B G
dequeue B
enqueue A D
dequeue G
enqueue I
dequeue A
dequeue D
enqueue C E
dequeue I
enqueue H
dequeue C
dequeue E
dequeue H

[edit]Sample implementations

preorder(node)
  if node = null then return
  print node.value
  preorder(node.left) 
  preorder(node.right)
inorder(node)
  if node = null then return
  inorder(node.left)
  print node.value
  inorder(node.right)
postorder(node)
  if node = null then return
  postorder(node.left)
  postorder(node.right)
  print node.value


Power Point Representation

Memory Leak in Java


What is memory leak in java? How to find it? and how to solve the memory leak?
Actually there is  not to worry about the memory leak in Java.
It is handled by Garbage Collector in Java.
 
But sometimes if there is java.lang.OutOfMemoryError Exception , memory leak is certainly strong suspect.
 
IF any application eats more & more system memory and never seems to return memory back to the system untill large amount ot physical memory allocation to that application then this is the sign of memory leak.
 
Also there is a common problem when we register a class as an event listener without bothering to unregister when the class is no longer needed.
 
Some Memory debugging programs can come in handy when you're trying to detect memory leaks. These r better that task manager.
 
We can prevent memory leaks by watching for some common problems. Collection classes, such as hashtables and vectors, are common places to find the cause of a memory leak. This is particularly true if the class has been declared static and exists for the life of the application. and many times member variables of a class that point to other classes simply need to be set to null at the appropriate time.

Tuesday, 3 January 2012

Basics Sorting Algorithmes


/***************** Bubble Sort **************/

public void bubbleSort(int[] arr) {
      boolean swapped = true;
      int j = 0;
      int tmp;
      while (swapped) {
            swapped = false;
            j++;
            for (int i = 0; i < arr.length - j; i++) {                                       
                  if (arr[i] > arr[i + 1]) {                          
                        tmp = arr[i];
                        arr[i] = arr[i + 1];
                        arr[i + 1] = tmp;
                        swapped = true;
                  }
            }                
      }
}
/************ Selection Sort ***********/


public void selectionSort(int[] arr) {
      int i, j, minIndex, tmp;
      int n = arr.length;
      for (i = 0; i < n - 1; i++) {
            minIndex = i;
            for (j = i + 1; j < n; j++)
                  if (arr[j] < arr[minIndex])
                        minIndex = j;
            if (minIndex != i) {
                  tmp = arr[i];
                  arr[i] = arr[minIndex];
                  arr[minIndex] = tmp;
            }
      }
}
/*************** Insertion Sort **************/

void insertionSort(int[] arr) {
      int i, j, newValue;
      for (i = 1; i < arr.length; i++) {
            newValue = arr[i];
            j = i;
            while (j > 0 && arr[j - 1] > newValue) {
                  arr[j] = arr[j - 1];
                  j--;
            }
            arr[j] = newValue;
      }
}

/************************* Quick Sort *******************/

int partition(int arr[], int left, int right)
{
      int i = left, j = right;
      int tmp;
      int pivot = arr[(left + right) / 2];
     
      while (i <= j) {
            while (arr[i] < pivot)
                  i++;
            while (arr[j] > pivot)
                  j--;
            if (i <= j) {
                  tmp = arr[i];
                  arr[i] = arr[j];
                  arr[j] = tmp;
                  i++;
                  j--;
            }
      };
     
      return i;
}

void quickSort(int arr[], int left, int right) {
      int index = partition(arr, left, right);
      if (left < index - 1)
            quickSort(arr, left, index - 1);
      if (index < right)
            quickSort(arr, index, right);
}

/*********************** Merge Sort ***************/
public void merge(int[] A, int[] B, int[] C) {
      int i, j, k, m, n;
      i = 0;
      j = 0;
      k = 0;
      m = A.length;
      n = B.length;
      while (i < m && j < n) {
            if (A[i] <= B[j]) {
                  C[k] = A[i];
                  i++;
            } else {
                  C[k] = B[j];
                  j++;
            }
            k++;
      }
      if (i < m) {
            for (int p = i; p < m; p++) {
                  C[k] = A[p];
                  k++;
            }
      } else {
            for (int p = j; p < n; p++) {
                  C[k] = B[p];
                  k++;
            }
      }
}