Monday, 6 November 2017

How to generate random bytes in Java?

There are many ways to generate random bytes in Java.

         a. Using nextBytes() method of Random class
         b. Using nextBytes method of SecureRandom class
         c. Using SecureRandom.getInstanceStrong().nextBytes(bytes)
         d. Using ThreadLocalRandom.current().nextBytes(bytes)
        
Using nextBytes() method of Random class
Random class provides nextBytes() method, it takes a byte array as argument and fill the input byte array with random bytes.

                 Random random = new Random();
                 byte[] b = new byte[20];
                 random.nextBytes(b);
                
RandomDemo.java
package com.sample.Random;

import java.util.Random;

public class RandomDemo {
  private static void printArray(byte[] byteArr) {
    for (byte b : byteArr) {
      System.out.print(b + ",");
    }
  }

  public static void main(String args[]) {
    Random random = new Random();
    byte[] b = new byte[20];
    random.nextBytes(b);
    printArray(b);
  }
}

Sample Output
-56,108,-21,-73,83,1,-2,-117,-52,-66,-96,-51,89,-79,100,-106,121,68,79,81,

Using nextBytes method of SecureRandom class
'java.security.SecureRandom' class provides nextBytes method, it takes byte array as argument and fill the byte array with random bytes. I would prefer to use Secure Random to generate random numbers than Random. It is because, Random class uses System clock to generate the seed, where as SecureRandom class uses random data from operating system (For ex interval betweem keystorkes, cpul cycles etc.,) to generate the seed. SecureRandom is more secure as compared to Random.

                 SecureRandom random = new SecureRandom();
                 byte[] b = new byte[20];
                 random.nextBytes(b);
                

RandomDemo.java
package com.sample.Random;

import java.security.SecureRandom;

public class RandomDemo {
  private static void printArray(byte[] byteArr) {
    for (byte b : byteArr) {
      System.out.print(b + ",");
    }
  }

  public static void main(String args[]) {
    SecureRandom random = new SecureRandom();
    byte[] b = new byte[20];
    random.nextBytes(b);
    printArray(b);
  }
}

Sample Output
9,62,-83,114,6,70,68,-63,-94,33,-100,-75,-91,-36,-60,-26,27,-116,64,-113,

Using SecureRandom.getInstanceStrong().nextBytes(bytes)
SecureRandom.getInstanceStrong() is avialble in Java1.8. 'SecureRandom.getInstanceStrong()' returns a secure random object that was selected by using the algorithms/providers specified in the securerandom.strongAlgorithms (Ex: Windows-PRNG:SunMSCAPI,SHA1PRNG:SUN)

Get the algorithms specified in 'securerandom.strongAlgorithms'
By using below statements, you can get the algorithms specified in 'securerandom.strongAlgorithms' property
                 String randomAlgorithms = Security.getProperty("securerandom.strongAlgorithms");
                 System.out.println(randomAlgorithms);

Below statements are used to generate random bytes.
                 SecureRandom random = SecureRandom.getInstanceStrong();
                 byte[] b = new byte[20];
                 random.nextBytes(b);
        

RandomDemo.java
package com.sample.Random;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class RandomDemo {
  private static void printArray(byte[] byteArr) {
    for (byte b : byteArr) {
      System.out.print(b + ",");
    }
  }

  public static void main(String args[]) throws NoSuchAlgorithmException {
    SecureRandom random = SecureRandom.getInstanceStrong();
    byte[] b = new byte[20];
    random.nextBytes(b);
    printArray(b);

  }
}


Sample Output
73,-22,-8,-24,-80,-50,113,-33,-34,-69,104,-66,-74,-114,-104,-118,102,-26,-106,-72,

Prefer to use 'SecureRandom.getInstanceStrong()' over all other methods

Using nextBytes method of ThreadLocalRandom class
Below statements are used to generate random numbers.
                 ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
                 byte b[] = new byte[20];
                 threadLocalRandom.nextBytes(b);


RandomDemo.java
package com.sample.Random;

import java.security.NoSuchAlgorithmException;
import java.util.concurrent.ThreadLocalRandom;

public class RandomDemo {
  private static void printArray(byte[] byteArr) {
    for (byte b : byteArr) {
      System.out.print(b + ",");
    }
  }

  public static void main(String args[]) throws NoSuchAlgorithmException {

    ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
    byte b[] = new byte[20];
    threadLocalRandom.nextBytes(b);
    printArray(b);
  }
}





Friday, 3 November 2017

Implement a stream that writes to multiple streams

Implement a OutputStream such that, when you write some information to this stream, it will write to multiple streams.

One of my friend got this interview question, I feel interviewer asked this question to check how comfortable he is while handling streams. The question is abstract, but interviewer seems to be expecting whether the implementation is handling all the cases or not.

Let’s break the question into small tokens.

When you write some information to the stream it should write to multiple streams.
From this statement, it is clear that the stream that we are going to implement should handle multiple output streams.
public class MultiOutputStream extends OutputStream {

 private List<OutputStream> outStreams;

 public MultiOutputStream(OutputStream... outputStreams) {

  if (outputStreams == null) {
   throw new IllegalArgumentException("outputStreams should not be null");
  }

  outStreams = new ArrayList<>();

  for (OutputStream outStream : outputStreams) {
   if (outStream != null) {
    outStreams.add(outStream);
   }
  }
 }

 .....
 .....
 .....
}

Override write methods
Since OutputStream writes information to the streams, we need to override write methods such that, whenever you call write method on this stream, it should call the write operation on all underlying streams.
 @Override
 public void write(int b) throws IOException {
  for (OutputStream outputStream : outStreams) {
   outputStream.write(b);
  }
 }

What about flush and close operations?
Implementation is similar like how we implemented write method in previous step. Whenever user calls flush, we need to flush all the underlying streams and whenever close() is called on this stream, it should close all the underlying streams.
 @Override
 public void flush() throws IOException {
  for (OutputStream outputStream : outStreams) {
   outputStream.flush();
  }
 }

 @Override
 public void close() throws IOException {
  for (OutputStream outputStream : outStreams) {
   outputStream.close();
  }
 }


Find the below working application.

MultiOutputStream.java
package com.sample.streams;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Output stream class to write to multiple streams.
 * 
 *
 */
public class MultiOutputStream extends OutputStream {

 private List<OutputStream> outStreams;

 public MultiOutputStream(OutputStream... outputStreams) {

  if (outputStreams == null) {
   throw new IllegalArgumentException("outputStreams should not be null");
  }

  outStreams = new ArrayList<>();

  for (OutputStream outStream : outputStreams) {
   if (outStream != null) {
    outStreams.add(outStream);
   }
  }
 }

 @Override
 public void write(int b) throws IOException {
  for (OutputStream outputStream : outStreams) {
   outputStream.write(b);
  }
 }

 @Override

 public void write(byte b[]) throws IOException {
  for (OutputStream outputStream : outStreams) {
   outputStream.write(b);
  }
 }

 @Override
 public void write(byte b[], int off, int len) throws IOException {
  for (OutputStream outputStream : outStreams) {
   outputStream.write(b, off, len);
  }
 }

 @Override
 public void flush() throws IOException {
  for (OutputStream outputStream : outStreams) {
   outputStream.flush();
  }
 }

 @Override
 public void close() throws IOException {
  for (OutputStream outputStream : outStreams) {
   outputStream.close();
  }
 }
}

Test.java
package com.sample.streams;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;

public class Test {
 public static void main(String args[]) throws IOException {

  PrintStream fileStream1 = new PrintStream(new FileOutputStream("outputFile1.log", true));
  PrintStream fileStream2 = new PrintStream(new FileOutputStream("outputFile2.log", true));

  try (MultiOutputStream multiOutputStream = new MultiOutputStream(fileStream1, fileStream2, System.out)) {
   multiOutputStream.write(new String("Hello World").getBytes());
  }

 }
}



Thursday, 2 November 2017

Redirect System out and error messages to files programmatically

java.lang.System class provides setErr, setOut methods to reassign error and output streams. In this post, I am going to show how to redirect the 'System.out' messages to 'output.log' and error messages to 'error.log' by using setOut and setErr methods.

Below step-by-step procedure explains how to redirect the output and error messages to output.log and error.log files.

Step 1: Define two PrintStream instances, one should point to 'output.log' and other should point to 'error.log'.
PrintStream pOut = new PrintStream(new FileOutputStream("output.log", true));
PrintStream pErr = new PrintStream(new FileOutputStream("error.log", true));

Step 2: Set the output and error streams using setOut and setErr methods
System.setOut(pOut);
System.setErr(pErr);

Find the below working application.

Test.java
package com.sample.streams;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

public class Test {
 public static void main(String args[]) throws FileNotFoundException {

  try (PrintStream pOut = new PrintStream(new FileOutputStream("output.log", true));
    PrintStream pErr = new PrintStream(new FileOutputStream("error.log", true))) {
   System.setOut(pOut);
   System.setErr(pErr);

   System.out.println("Hello World");
   System.err.println("Got Error");
  }

 }
}

Wednesday, 1 November 2017

Remove element at given index from array

In java, arrays are fixed in size, you can’t increase/decrease the size of the array after initialization. To solve this problem, we need to return new array by not including the element at given index of input array.

Below code snippet do that.
 public static Object removeEleAtIndex(Object array, int index) {
  if (array == null || index < 0) {
   return array;
  }

  int length = Array.getLength(array);

  if (index > length - 1) {
   return array;
  }

  Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);

  System.arraycopy(array, 0, result, 0, index);
  System.arraycopy(array, index + 1, result, index, length - index - 1);
  return result;
 }

Find the below working application.

ArrayUtil.java
package com.sample.collections;

import java.lang.reflect.Array;

public class ArrayUtil {

 /**
  * Remove element at given index and return new array
  * 
  * @param array
  * @param index
  * 
  * @return array, if array is null (or) index < 0 (or) index is > number of
  *         elements in array
  */
 public static Object removeEleAtIndex(Object array, int index) {
  if (array == null || index < 0) {
   return array;
  }

  int length = Array.getLength(array);

  if (index > length - 1) {
   return array;
  }

  Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);

  System.arraycopy(array, 0, result, 0, index);
  System.arraycopy(array, index + 1, result, index, length - index - 1);
  return result;
 }

 public static void printArrayToConsole(Object array) {
  for (int i = 0; i < Array.getLength(array); i++) {
   System.out.println(Array.get(array, i));
  }
 }
}


Test.java
package com.sample.collections;

public class Test {

 public static void main(String args[]) {
  int[] arr = { 2, 3, 5, 7, 11, 13, 17 };

  int[] result = (int[]) ArrayUtil.removeEleAtIndex(arr, 4);
  ArrayUtil.printArrayToConsole(result);
 }
}


Tuesday, 31 October 2017

What is the problem with type erasure?

Type Erasure is a process, where Java Compiler replaces type with its first bound if the type parameter is bounded, or Object if the type parameter is unbounded.

Let me explain with an example,

Box.java
public class Box<T> {

    private T data;

    public Box(T data) {
        this.data = data;
    }

    public T getData() { return data; }

}

“T” is unbounded type in Box class. So Java Compiler replaces Every Occurrence of T with Object. After compilation, above class will be converted like below.


Box.java
public class Box {

    private Object data;

    public Box(Object data) {
        this.data = data;
    }

    public Object getData() { return data; }

}

let us see one more Example with bounded type.


Box.java
public class Box<T extends Integer> {

    private T data;

    public Box(T data) {
        this.data = data;
    }

    public T getData() { return data; }

}


After type Erasure, Type Parameter “T” will be converted to Integer.
Box.java
public class Box{

    private Integer data;

    public Box(Integer data) {
        this.data = data;
    }

    public Integer getData() { return data; }

}


What is the problem with type erasure?
a.   Since type erasure erase the type information, there is no way to get the type information at run time.
b.   Because of the type erasure, you may add one type of object to collection of other type. This makes the application fails at run time.
MyCollection.java
package utils;

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

public class MyCollection<T> {

 private List<T> myList = new ArrayList<> ();
 
 @SuppressWarnings("unchecked")
 public void addToList(Object obj){
  myList.add((T) obj);
 }
 
 public void printCollection(){
  for(T obj : myList){
   System.out.println(obj);
  }
 }
}
Test.java
package utils;

public class Test {

 public static void main(String args[]) throws CloneNotSupportedException {
  MyCollection<Integer> collection = new MyCollection<>();

  collection.addToList("krishna");
  collection.addToList(1234);
  collection.addToList(123.456);

  collection.printCollection();
 }
}

Even though I defined the collection myList is of type Integer, I can able to add all types of objects to the collection. Compiler is unable to catch this kind of problems.

How to identify above kind of problems?
Before adding the elements to the collection, we can cast the elements using ‘cast’ method of java.lang.Class. ‘cast’ method throws ‘ClassCastException’, if it is unable to cast the object to given type.

Find the below working application.

MyCollecton.java
package utils;

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

public class MyCollection<T> {

 private List<T> myList = new ArrayList<>();
 private final Class<T> myClass;

 public MyCollection(Class<T> myClass) {
  this.myClass = myClass;
 }

 public void addToList(Object obj) {
  myList.add(myClass.cast(obj));
 }

 public void printCollection() {
  for (T obj : myList) {
   System.out.println(obj);
  }
 }
}

Test.java
package utils;

public class Test {

 public static void main(String args[]) throws CloneNotSupportedException {
  MyCollection<Integer> collection = new MyCollection<>(Integer.class);

  collection.addToList("krishna");
  collection.addToList(1234);
  collection.addToList(123.456);

  collection.printCollection();
 }
}


When you ran above program, you will end up in below error.

Exception in thread "main" java.lang.ClassCastException: Cannot cast java.lang.String to java.lang.Integer
    at java.lang.Class.cast(Unknown Source)
    at utils.MyCollection.addToList(MyCollection.java:16)
    at utils.Test.main(Test.java:8)

You may like