Search This Blog

Monday, 6 May 2013

Read InputStream twice from HttpRequest


package xxx.xxx.xxx;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.cert.X509Certificate;
import java.util.HashMap;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sun.xml.internal.ws.util.ByteArrayBuffer;

/**
 *
 * @author Atul Kumar
 */
public class AuthenticationFilter implements Filter {

private final Log log = LogFactory.getLog(this.getClass());
private static final int buffSize = 4096;

@Override
public void destroy() {
log.debug("Authentication Filter Destroyed");
}

// convert InputStream to String
private static String getStringFromInputStream(HttpServletRequestWrapperX httpRequest) {

ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
IOUtils.copy(httpRequest.getInputStream(), baos);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte[] bytes = baos.toByteArray();
return new String(bytes);
}

@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
log.info("Authentication Filter doFilter called");
// HttpServletRequest httpRequest2 = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;


HttpServletRequestWrapperX httpRequest = new HttpServletRequestWrapperX(
(HttpServletRequest) request);
log.debug("In filter  - " + getStringFromInputStream(httpRequest));

filterChain.doFilter(httpRequest, response);
}
}

@Override
public void init(FilterConfig arg0) throws ServletException {
log.info("Authentication Filter Initialized");
}

private static class HttpServletRequestWrapperX
extends
HttpServletRequestWrapper  {

private final String body;

public HttpServletRequestWrapperX(HttpServletRequest request) {
super(request);

StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;

try {
InputStream inputStream = request.getInputStream();

if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(
inputStream));

char[] charBuffer = new char[128];
int bytesRead = -1;

while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append("");
}
} catch (IOException ex) {
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
}
}
}

body = stringBuilder.toString();
}

@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
body.getBytes());

ServletInputStream inputStream = new ServletInputStream() {
public int read() throws IOException {
return byteArrayInputStream.read();
}
};

return inputStream;
}
}
}

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.