Thursday, 16 July 2015

In Java to encode Base64 in Java


  • Base64 is a straight forward encoding for binary data into readable characters.
  • The Java class is the javax.xml.bind.DatatypeConverter, which is part of the XML package (JAXB) and has a method called printBase64Binary() that takes in a byte array and returns a encoded BASE64 string.
  • The following is a code snippet that encoding the user name and password for BASIC Authentication for Web applications.
  • It combines a user name and corresponding password with “:” as delimiter, and converts it to an byte array that can be feed into the printBase64Binary(). Once the encoded string is ready, just set it as value to the Authorization header. 

The following code is how to do the encoding and set it as a HTTP header in request to server:
     
import javax.xml.bind.DatatypeConverter;

String encoding = 
DatatypeConverter.printBase64Binary((username + ":" + password).getBytes("UTF-8"));
  
urlConn.setRequestProperty("Authorization", "Basic " + encoding);


Depending the client library, your API to set the header could be different. For example, if you use Apache Thrift’s HTTP transport, the code may look like the following:

import org.apache.thrift.transport.THttpClient;
 
transport.setCustomHeader("Authorization", "Basic " + encoding);

Sunday, 28 June 2015

How to calculate difference of date and time in Java


To calculate date and time difference with manual calculation...

  • Very first step to convert date into milliseconds (ms)
    • String date1 = "01-02-2015 09:15:20";
    • SimpleDateFormat format = new  SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      • HH convert into 24 hours format (0-23)
      • hh convert into 12 hours format
    •  Date d1 = format.parse(date1);
    • long ms = d1.getTime();


Thursday, 25 June 2015

Angular JS Directice in IE8


  • The most powerful feature Directive in Angular JS. 
  • Allow you to create custom reusable components. 
  • Few exception are there...keep in mind..!!!
  • With IE8 Angular Js should work consistent like other browser.
  • Four ways to create directive
    1. Angular JS viz. Attribute  (Common One)
    2. Element (Common One)
    3. Class
    4. Comment
  •  Let take one example :
    • Your directive is like : <div my-js-control>....</div>
    • Now use this directive in IE8
    • Copy following syntax and paste it in your HTML/JSP page.
<Html>
    <head>

   <!--[if lte IE 8]>
      <script>
        document.createElement('div-my-js-control');
      </script>
    <![endif]-->

   </head>
</html>


  • This document.createElement() creates an element called 'my-js-control' which can use in application.
  • If you create more than one directive in your system then you need to create that many new elements for older browser
  • Long story short : It is preferable to use Angular JS directive in IE8 as attributes.




Friday, 3 April 2015

public class A {
   public static void main(String[] args) {
      

     Integer i1=100; Integer i2=100;
     System.out.println(i1==i2);//true
    

     Integer i3=200; Integer i4=200;
    System.out.println(i3==i4);//false ??
   }
}


Conclusion :

  • The Integer wrapper class interns the objects from -127 to +128. So all Integers with a value less than 128 are the same as they are interned. The values greater than 128 are not the same because they are not interned.
  • The JVM will create a cache of objects(something similar to the string constant pool) for the above range and assigns the same object(if it already exists) when ever a new object with the same value is created. So in your case, the two Integers for 100 will use the same object and the ones for 200 won't be the same.
  • you assign a integral literal to a Integer reference, it will invoke the Integer.valueOf(..) method.
  • This method uses the famous Fly-weigh pattern. That is that the -128~127 integers are cached. So the "i1==i2" will be true. Of course, you can change the cache range by setting IntegerCache.low or IntegerCache.high which are static variables.
  • Always compare wrapper classes with equals(e).

     
     
     
     
     

Wednesday, 3 September 2014

Java : Externalizable vs Serializable

  • Externalizable is an interface that enables you to define custom rules and your own mechanism for serialization. Serializable defines standard protocol and provides out of the box serialization capabilities.
  • Externalizable extends Serializable.
  • Implement writeExternal and readExternal methods of the Externalizable interface and create your own contract / protocol for serialization.
  • Saving the state of the supertypes is responsibility of the implementing class.
  • You might have seen in my previouse article on how to customize the default implementation of Serializable. These two methods readExternal and writeExternal (Externalizable) supersedes this customized implementation of readObject and writeObject.
  • In object de-serialization (reconsturction) the public no-argument constructor is used to reconstruct the object. In case of Serializable, instead of using constructor, the object is re-consturcted using data read from ObjectInputStream.
  • The above point subsequently mandates that the Externalizable object must have a public no-argument constructor. In the case of Seriablizable it is not mandatory.
  • Behaviour of writeReplace and readResolve methods are same for both Serializable and Externalizable objects. writeReplace allows to nominate a replacement object to be written to the stream. readResolve method allows to designate a replacement object for the object just read from the stream.
  • In most real time scenarios, you can use Serializable and write your own custom implementation for serialization by providing readObject and writeObject.
You may need Externalizable,
  1. If you are not happy with the way java writes/reads objects from stream.
  2. Special handling for supertypes on object construction during serialization.

Java : Call main method before JVM Call

Static blocks are also called Static initialization blocks . A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:
 
static {
// whatever code is needed for initialization goes here
}

 
A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code. 
 
And dont forget, this code will be executed when JVM loads the class. JVM combines all these blocks into one single static block and then executes. Here are a couple of points I like to mention:

public class Test {

    static {
        Test.main("From static Block");
    }


    public static void main(String... args) {
        if (args.length > 0) {
            System.out.println(args[0]);
        } else {
            System.out.println("By JVM");
        }
    }
}

Monday, 1 September 2014

Java Puzzel : OutOfMemory

Try compiling and running the code below - then uncomment for loop compile and run.
Why does this program have an error when for loop is commented out?