Tuesday, March 4, 2014

Generating Password Using SecureRandon class

Use of java.security.SecureRandom class



File 1: Passwordgenerator.java


import java.util.ArrayList;
import java.util.prefs.InvalidPreferencesFormatException;
import java.security.SecureRandom;
import java.text.ParseException;

public class Passwordgenerator {
private int length;

private boolean lowercaseIncluded;
private boolean numbersIncluded;
private boolean othersIncluded;
private boolean uppercaseIncluded;

private String password;
private String template;
static SecureRandom RANDOM = new SecureRandom();
Passwordgenerator() {

password = "";
template = "";

length = 8;

lowercaseIncluded = true;
uppercaseIncluded = true;
numbersIncluded = true;

othersIncluded = true;
generatePassword();
}
private boolean flagsOK() {
return lowercaseIncluded
|| uppercaseIncluded
|| numbersIncluded
|| othersIncluded;
}
private static char randomLowercase() {



char c =(char) (97 + (int) (RANDOM.nextDouble() * 26));
if(c=='l'){
return randomLowercase();
}
return c;
}
private static char randomUppercase() {

char c = (char) (65 + (int) (RANDOM.nextDouble() * 26));
if(c=='I'){
return randomUppercase();
}
return c;
}
private static char randomOther() {
char c =(char) (33 + (int) (RANDOM.nextDouble() * 15));
//if(c=='"'){
return '!';
//}
//return c;
}


/**
* @return a random character from '0' to '9'
*/
private static char randomNumber() {



return (char) (48 + (int) (RANDOM.nextDouble() * 10));
}

public void generatePassword() /* throws InvalidPreferencesFormatException, ParseException */ {
  // clear password if necessary
if (password.length() != 0) {
password = "";
}


if (template.length() > 0) {
length = template.length();
for (int i = 0; i < length; i++) {

switch (template.charAt(i)) {
case 'a' :
password += randomLowercase();
break;

case 'A' :
password += randomUppercase();
break;

case 'n' :
case 'N' :
password += randomNumber();
break;

case 'o' :
case 'O' :
password += randomOther();
break;

}
}
} else {

ArrayList flags = new ArrayList();
if (lowercaseIncluded) {
flags.add(new randomLowercase());
}
if (uppercaseIncluded) {
flags.add(new randomUppercase());
}
if (othersIncluded) {
flags.add(new randomOther());
}
if (numbersIncluded) {
flags.add(new randomNumber());
}

int flagLength = flags.size();



for (int i = 0; i < length; i++) {

               password += ((randomCharacter) flags.get( (int) (RANDOM.nextDouble() * flagLength)  ))
                       .execute();
}
}
}

/**
* @return the length of the generated password
*/
public int getLength() {
return length;
}

/**
* @return the generated password
*/
public String getPassword() {
return password;
}

/**
* @return password template
*/
public String getTemplate() {
return template;
}
/**
* @return lowercaseIncluded
*/
public boolean isLowercaseIncluded() {
return lowercaseIncluded;
}

/**
* @return numbersIncluded
*/
public boolean isNumbersIncluded() {
return numbersIncluded;
}

/**
* @return othersIncluded
*/
public boolean isOthersIncluded() {
return othersIncluded;
}

/**
* @return uppercaseIncluded
*/
public boolean isUppercaseIncluded() {
return uppercaseIncluded;
}

/**
* @param length, enforced to be a positive integer >= 3.
*/
public void setLength(int length) {
this.length = (length < 3) ? 3 : length;
}

/**
* @param b
*/
public void setLowercaseIncluded(boolean b) throws InvalidPreferencesFormatException {
lowercaseIncluded = b;

// did we turn off the last flag?  if so
// turn it back on and report error
if (b == false && !flagsOK()) {
lowercaseIncluded = true;
throw new InvalidPreferencesFormatException("At least one flag must be on to generate a password");
}
}

/**
* @param b
*/
public void setNumbersIncluded(boolean b) throws InvalidPreferencesFormatException {
numbersIncluded = b;


if (b == false && !flagsOK()) {
numbersIncluded = true;
throw new InvalidPreferencesFormatException("At least one flag must be on to generate a password");
}
}

/**
* @param b
*/
public void setOthersIncluded(boolean b) throws InvalidPreferencesFormatException {
othersIncluded = b;

// did we turn off the last flag?  if so
// turn it back on and report error
if (b == false && !flagsOK()) {
othersIncluded = true;
throw new InvalidPreferencesFormatException("At least one flag must be on to generate a password");
}
}

/**
* @param string
*/
public void setTemplate(String template) throws ParseException {
// make sure the template contains only legal characters
for (int i = 0; i < template.length(); i++) {
switch (template.charAt(i)) {
case 'a' :
case 'A' :
case 'n' :
case 'N' :
case 'o' :
case 'O' :
break;

default :
throw new ParseException("Password template contains an invalid character", i);
}
}
this.template = template;
}

/**
* Clears the password template,making generation rely on the flags.
*
*/
public void clearTemplate() {
template = "";
}

/**
* @param b
*/
public void setUppercaseIncluded(boolean b) throws InvalidPreferencesFormatException {
uppercaseIncluded = b;

// did we turn off the last flag?  if so
// turn it back on and report error
if (b == false && !flagsOK()) {
uppercaseIncluded = true;
throw new InvalidPreferencesFormatException("At least one flag must be on to generate a password");
}
}

/*--------------------------------------------------------
Wrapper classes and interface to mimic the array of
function references functionality required.
----------------------------------------------------------*/
private static class randomLowercase implements randomCharacter {
public char execute() {
return Passwordgenerator.randomLowercase();
}
}

private static class randomUppercase implements randomCharacter {
public char execute() {
return Passwordgenerator.randomUppercase();
}
}

private static class randomOther implements randomCharacter {
public char execute() {
return Passwordgenerator.randomOther();
}
}

private static class randomNumber implements randomCharacter {
public char execute() {
return Passwordgenerator.randomNumber();
}
}

private static interface randomCharacter {
char execute();
}

}




File 2: Test.java


import java.security.SecureRandom;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Random;

public class Test {

/**
* @param args
*/
static String pwd;
public static void main(String[] args) {

String userName="mankar.m0(@gmail.com";
    try {
        boolean flag;
        String[] templets =
        { "aaAnanaA", "aaannnAnaA", "aanAnnnaA", "aAAnnAaaA", "aaAnaaAA","aaAnnnaA", "aaananAnaA", "aanAnnnaa", "aAAanAaan", "aaAnaaAn"  };
       
        System.out.println("Uniq ID "+new java.security.SecureRandom().nextLong());

        System.out.println("Uniq ID twwwwwo   "+new java.util.Random().nextLong());
       
        System.out.println("Math.random value of "+(Math.random()));
       
        System.out.println("SecureRandom value of "+new java.security.SecureRandom().nextDouble());
        Passwordgenerator passGen = new Passwordgenerator();
        SecureRandom RANDOM = new SecureRandom();
        //SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
       
        //passGen.setTemplate(templets[sr.nextInt(20)]);
       
        passGen.setTemplate(templets[(int)(RANDOM.nextDouble()*4)]);
       
        do {
        passGen.generatePassword();
        pwd = passGen.getPassword();
        flag = usernameCheck(userName, pwd);
        //flag will be true is the password is not correct
        } while (flag);

    } catch (ParseException e) {
   
    }catch(Exception e ){

    }
    System.out.println("Manish   "+pwd.length()+"  "+pwd);
   
    Test t1 = new Test();
    t1.generateId(10);
}

private static boolean  usernameCheck(String uname, String pwd) {
return (
(pwd.toLowerCase()).matches(".*" + (uname.toLowerCase()) + ".*"));
}

protected  String generateId( final int number )
{
 Random rand = new Random( number );

 //SecureRandom rand = new SecureRandom();

  StringBuffer id = new StringBuffer();
  String[] scrambled = new String[3];
  StringBuffer nonrandom = scrambleNumber( number );
  scrambled[0] = extractChar( scrambleNumber( rand.nextInt() ) );
  scrambled[1] = extractChar( scrambleNumber( rand.nextInt() ) );
  String first = nonrandom.substring( 0, 1 );
  String rest = nonrandom.substring( 1 );
  id.append( first );
  id.append( scrambled[0] );
  id.append( rest );
  id.append( scrambled[1] );
  System.out.println(id);
  return id.toString();
}

protected String extractChar( StringBuffer random )
{
  if ( random.length() > 3 ) {
    return random.substring( 3, 4 );
  }
  return random.substring( 0, 1 );
}
/**
 * <p>
 *
 * </p>
 * @param number the number
 * @return StringBuffer
 */
private StringBuffer scrambleNumber( final int number )
{
  int abs = Math.abs( number );
  int divisor = 27;
  int mod = abs % divisor;
  int div = abs / divisor;
  if ( div == 0 ) {
    return new StringBuffer( scrambleDigit( mod ) );
  } else {
    return scrambleNumber( div ).append( scrambleDigit( mod ) );
  }
}

private String scrambleDigit( final int digit )
{
  HashMap map = new HashMap();
  map.put( "0", "D" );
  map.put( "1", "N" );
  map.put( "2", "C" );
  map.put( "3", "K" );
  map.put( "4", "A" );
  map.put( "5", "M" );
  map.put( "7", "G" );
  map.put( "8", "X" );
  map.put( "9", "L" );
  map.put( "10", "H" );
  map.put( "11", "W" );
  map.put( "12", "4" );
  map.put( "13", "Y" );
  map.put( "14", "Q" );
  map.put( "15", "5" );
  map.put( "16", "J" );
  map.put( "17", "3" );
  map.put( "18", "E" );
  map.put( "19", "8" );
  map.put( "20", "V" );
  map.put( "21", "6" );
  map.put( "22", "T" );
  map.put( "23", "P" );
  map.put( "24", "B" );
  map.put( "25", "9" );
  map.put( "26", "F" );

  String key = digit + "";

  if(map.containsKey( key ))
  {
    return (String)map.get( key );
  }
  else
  {
    return "";
  }
}
}




Sunday, February 23, 2014

How to get path and file name of a uploading file in JSP/servlets using MultipartReuest

This is JSp example, same you can code in servlets.




<%@ page import="com.oreilly.servlet.MultipartRequest" %> 
<%@  page import="java.util.Enumeration" %>
<%@  page import="java.io.File" %>

<%
System.out.println("saurabh");
MultipartRequest m = new MultipartRequest(request, "d:/new");
out.println("Files:");
Enumeration files = m.getFileNames();
out.println("<pre>");
try{
while (files.hasMoreElements()) {
String name = (String)files.nextElement();
String filename = m.getFilesystemName(name);
String type = m.getContentType(name);
File f = m.getFile(name);
System.out.println("name: " + name);
System.out.println("filename: " + filename);
System.out.println("type: " + type);
if (f != null) {
       System.out.println("f.toString(): " + f.toString());
       System.out.println("f.getName(): " + f.getName());
       System.out.println("f.exists(): " + f.exists());
       System.out.println("f.length(): " + f.length());
       System.out.println();
}
System.out.println("</pre>");
}
}catch (Exception e1){
       System.out.println("<pre>");
       System.out.println("</pre>");
}
System.out.print("successfully uploaded");

  
%>

Tuesday, June 4, 2013

Collection Framework In Java



Collection Framework

  • It is the standardized mechanism of grouping of the similar or different types of objects into a single object. This single object is known as collection framework.
  • Aims/Characteristics of collection framework:
1)      Performance: - It provides performance & when we want to transfer ‘n’ number of records from the database to the main memory of the computer, keep all  those ‘n’ number of records into a single collection framework object and transfer if only one time.

2)      Collection framework provides EXTENDIBILITY. Arrays are also treated as collection framework objects but it is fixed in its size & it allows us to place parallel type of elements. But collection framework provides dynamic size & it allows us to add parallel or different types of objects.

3)      Adoptability: - Collection framework provides Adoptability features. Adoptability is the process of adding one collection object at the end of another collection object or at a specified position of another collection object.

4)      Efficient & Effective: - C/F is by default efficient & effective in organizing parallel or different types of objects in a single framework.

5)      Algorithmic Concepts: - C/F by default provides algorithmic oriented concepts & sorting techniques, searching techniques and preliminary data structure concept like stack, queue & trees.

  • One dimensional collection framework interfaces:
As a part of C/F we have following interfaces: -
1)      java.util.Collection;
2)      java.util.List;
3)      java.util.SortedSet;
4)      java.util.Queue;

  • Hierarchy chart of 1-D Collection Framework:


java.util.Collection:
(1)   Collection is an interface which allows us to organize the data in a single object by accepting parallel or different types of objects.

(2)   Collection framework is having the following features: -
(a) The interface Collection is available at the top of the hierarchy of all collection framework   
                  interfaces.
(b) Collection objects allow us to add duplicates or duplicate elements.
(c) Collection object allows us to insert an element at the end only.
(d) Collection object allows us to insert an element at the end only.
(e) Collection object allows us to retrieve the data only in the forward direction.
(f) Collection object displays the data in that order in which order we have added.

java.util.List:
(1)   The interface List extends the Collection interface.
(2)   An object of List allows us to add duplicates of List.
(3)   List objects allow us to add element either at the end or at any specified position.
(4)   List object allows us to retrieve the data in forward direction, in backward direction & in random direction.
(5)   List object always displays the data in sequential order.

java.util.Set:
(1)   Set extends Collection interface.
(2)   Set object does not allow duplicate elements.
(3)   Set object allows us to add an element at the end position only.
(4)   Set object allows us to retrieve the data in forward direction only.
(5)   Set object displays the data in that order in which order we have added.

java.util.SortedSet:
(1)   SortedSet extends Set interface.
(2)   An object of SortedSet does not allows us to add duplicates of List 
(3)   SortedSet objects allow us to add element either at the end position only  .
(4)   SortedSet object allows us to retrieve the data in forward direction only.
(5)   SortedSet object always displays the data in sequential order.

  • Methods in java.util.Collection:
1)      public int size() : - This method is used to find the number of elements of collection objects.
2)      public boolean add(Object): - This method is used for adding an object to the collection framework object.
a.       As long as we call this method to add the object to Collection Interface object & List Interface object, this method returns true, since they allow duplicates.
b.      When we call this method, by Set Interface object & SortedSet Interface Object, for adding elements, there is a possibility of returning false, since Set objects and SortedSet objects do not allows dublicates.

3)      public boolean addAll(Collection): -This method is used for adding one collection object at the end of another collection object. (called Adoptability)

4)      public Iterator iterator() : - this method is used for retrieving the objects from Collection Object, one by one.
Iterator is an Interface, which contains the following methods:-
            public boolean hasNext()
            public Object next()

public boolean hasNext() : - This method is used for determining weather the Iterator has next element or not. If it is having the next element then it returns true, or else it returns false.
     
public Object next() : - This method is used for obtaining the next element as long as hasNext() returns true.

  • Methods in java.util.List : -
1)      public void add(int, object): - This method is used for adding the element at the specified position.
2)      public void addAll(int,Collection) : -  This method is used for adding one List object to the another List object at an specified position.
3)      public Object get(int) : - This method is used for retrieving an element of List by passing a valid position.
4)      Public ListIterator listIterator() : - This method is used for retrieving the elements of the List one by one either in forward direction or in backward direction.
ListIterator is an interface which contains the following methods: -
a)      public boolean hasPrevious()
b)      public Object previous()
Iterator is the base interface for ListIterator.
hasPrevious() returns True, if ListIterator Object is having previous element otherwise Fasle.
previous() is used for obtaining previous element as long as hasPrevious returns true.
  • Methods in java.util.Set:
            This interface does not contain any special methods except collection method
  • Methods in java.util.SortedSet : -
1)      public Object first(): - This method is used for obtaining first Object in SortedSet.
2)      public Object last(): - This method is used for obtaining the last object in SortedSet.
3)      public SortedSet headset(Object obj): -  This method is used to obtain those objects which are less than or equal to  the target object.
4)      public SortedSet tailSet(Object obj) : - This method is used for obtaining those objects which are greater than the target object.
5)      public SortedSet subset(Object obj1,Object obj2) : - This method is used for obtaining those objects which are greater then or equal to the target object, obj1 & less than target object , obj2.

  • Following are the classes and interfaces of the java.util package:

    • Core Collection Interfaces:
(1)   Collection
(2)   Set
(3)   SortedSet
(4)   List
(5)   Map
(6)   SortedMap
    • Concrete Implementation:
(1)   ArrayList
(2)   HashMap
(3)   HashSet
(4)   HashTable
(5)   LinkList
(6)   Properties
(7)   Stack
(8)   TreeMap
(9)   TreeSet
(10)           Vector
(11)           WeakHashMap
  • Abstract Implementaion : -
(1)   AbstractCollection:
(2)   AbstractList
(3)   AbstractMap
(4)   AbstractSequentialList
(5)   AbstractSet
(6)   Dictionary
o   Infrastructure Interface:
(1)   Iterator
(2)   ListIterator
(3)   Comparable (java.lang)
(4)   Comparator
o   Infrastructor Classes:
(1)   Collections
(2)   Arrays 
o   .Date & its supporting Calendar Classes
o   Locale & its supporting ResourceBundle classes
o   BitSet
o   Important additional interfaces:
(1)   Enumeration
(2)   Observer (and Observable classes)
(3)   EventListener

Java's Collection Framework
  • A collections framework is a unified architecture for representing and manipulating collections. It has:
    • Interfaces: abstract data types representing collections
    • Implementations: concrete implementations of the collection interfaces
    • Algorithms: methods that perform useful computations, such as searching and sorting
    • These algorithms are said to be polymorphic: the same method can be used on different implementations
  • An interface describes a set of methods:
    • No constructors or instance variables
  • Interfaces must be implemented by classes
    • Classes guaranteed to have the same methods
    • Objects can be treated as the same type
    • Can use different algorithms / instance variables

Implementations:
  • A collection class
    • implements an ADT as a Java class
    • implements all methods of the interface
    • selects appropriate instance variables
    • can be instantiated
  • Java implements interfaces with
    • List: ArrayList, LinkedList, Vector
    • Map: HashMap, TreeMap
    • Set: TreeSet, HashSet
Algorithms:
Two Useful ADTs:
  • List: a collection with a first element, a last element, distinct predecessors and successors
    • duplicates that "equals" each other are allowed
  • Map: maps keys to values
    • Maps cannot contain duplicate keys
    • Each key maps at most one value
List:
  • A list is
    • a collection of elements (numbers, strings, accounts, pictures,…)
    • ordered (a sequence): there is a first, and a last element
      • lists can be empty – no elements
      • elements with a unique predecessor and successor
      • also known as a sequence
o   Peruse the Java 5 List Interface

ArrayList: A Java Collection Class that Implements List.
  • ArrayList:
    • stores a collection of any type of object 
    • can be all the same type, or different types
    • similar functionality to an array, but does not use subscripts
    • is an indexed collection

  • ArrayList JavaÔ: Resizable array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list.

The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.

  • List implemented by 3 classes:
// Interface name: List
// Three classes that implement the List interface:
List<String> bigList = new ArrayList<String>();
List<String> littleList = new LinkedList<String>();
List<String> sharedList = new Vector<String>();
// All three have an add method
bigList.add("in array list");
littleList.add("in linked list");
sharedList.add("in vector");

// All three have a get method
assertEquals("in array list", bigList.get(0));
assertEquals("in linked list", littleList.get(0));
assertEquals("in vector", sharedList.get(0));

Generics:
  • A List can be made to store only one type

            List<BankAccount> accountList =  new ArrayList<BankAccount>();
accountList.add(new BankAccount("One", 111.11));
accountList.add(new BankAccount("Two", 222.22));
accountList.add(new BankAccount("Three", 333.33));
            accountList.add(new BankAccount("Four", 444.44));
System.out.println(accountList.toString());

Output
[One $111.11, Two $222.22, Three $333.33, Four $444.44]

Iterators:
  • Iterators provide a general way to traverse all elements in a collection
  
            ArrayList<String> list = new ArrayList<String>();
            list.add("1-FiRsT");
            list.add("2-SeCoND");
            list.add("3-ThIrD");
            Iterator<String> itr = list.iterator();
            while (itr.hasNext()) {
            System.out.println(itr.next().toLowerCase());

Output
1-first
2-second
3-third

Enhanced for loop:
  • If a class extends Iterable<E> (like you did with your Set<E> class), you can use Java's enhanced for loop of this general form
for (E refVar : collection<E> ) {
                        refVar refers to each element in collection<E>
}
  • Example
ArrayList<String> list = new ArrayList<String>();
list.add("first");
for (String s : list)
System.out.println(s.toLowerCase());

Map and SortedMap:
  • The Map interface defines methods
    • get, put, contains, keySet, values, entrySet
  • TreeMap implements Map
    • put, get, remove: O(log n)
  • HashMap implements Map
    • put, get, remove: O(1)

Set and SortedSet:
  • Some Map methods return Set
  • The Set interface
    • add, addAll, remove, size, but no get!
  • Some implementations
    • TreeSet: values stored in order, O(log n)
    • HashSet: values in a hash table, no order, O(1)

Set up a small collection of mappings
Map<String, BankAccount> tm = new TreeMap<String, BankAccount>();

tm.put("M", new BankAccount("Michel", 111.11));
tm.put("G", new BankAccount("Georgie", 222.22));
tm.put("S", new BankAccount("Sam", 333.33));
tm.put("P", new BankAccount("Pei", 444.44));
tm.put("Z", new BankAccount("Zac", 555.55));

// Coming up: Some Map methods
keySet()

// Get the set of keys in the Map.
 // With TreeMap, the keys are ordered.
 Set<String> keys = tm.keySet();
 assertEquals("[G, M, P, S, Z]", keys.toString());

values()
// The values
Collection<BankAccount> accountCollection = tm.values();
Iterator<BankAccount> itr =
             accountCollection.iterator();
double allTheMoney = 0.0;
while (itr.hasNext()) {
allTheMoney += itr.next().getBalance();
}
assertEquals(1666.65, allTheMoney, 0.01);

entrySet()
// The mappings
Collection<Entry<String, BankAccount>> mapping =tm.entrySet();
Iterator<Entry<String, BankAccount>> itr2 = 
mapping.iterator();
while (itr2.hasNext()) {
System.out.print("<" +itr2.next().toString()+ ">  ");
}
<G=Georgie $222.22>  <M=Michel $111.11> 
<P=Pei $444.44>  <S=Sam $333.33>  <Z=Zac $555.55>
Maps do not have an iterator.