Thursday, 15 August 2013

Spring Basic Interview Questions Part-2 !



Interview Questions

Question: -What is spring?

Answer: -Spring is a lightweight open source framework created to address the complexity of enterprise application development. The layered architecture of this framework is the main advantage, which provides an option for the selection of existing spring modules which we want to use depends upon the requirement. It also provides a well integrated framework for J2EE application development.

Question: -What are the benefits of spring framework?

Answer: -Below are the benefits of spring framework:-

Lightweight: -As per the size and transparency, spring is a very lightweight framework. The Basic version of spring is about 1 MB. Spring does not use much memory and CPU processing head for loading beans. It is a light weight container as compare to other J2EE containers.

Container: -Spring framework container contains and manages the life cycle and configuration of application objects.

Aspect oriented (AOP):- This framework supports Aspect oriented programming. It also provides support for separating the business logic from system services by enabling cohesive development (well-integrated).

Inversion of control (IoC):- Inversion of control is a technique using which we can achieve loose coupling. Inversion of Control pattern tells that no need to create our objects but we should describe how they should be created. No need to directly connect with our components and services together in the code but we should describe which services are needed by which components in a configuration file. A container which is not but spring framework (IOC container) is then responsible for hooking it all up.

JDBC Exception Handling: - Spring provides a meaningful exception hierarchy, which helps to simplify the error handling strategy in Spring JDBC module. It also provides best Integration and well managed services with Hibernate, JDO and iBATIS.

Transaction Management: - It provides a generic abstraction layer for transaction management. This framework provides an option to the developer to add the pluggable transaction managers, and making it easy to set boundaries for transactions without dealing with low-level issues. It assembles several transaction management APIs.

Question: - How many modules are available in spring framework?

Answer: -spring is divided into seven modules which are:-



                                                                  Spring modules

Spring-core container: - spring core container provides the basic and essential functionality of the spring framework. BeanFactory is the primary component of the core container, which is the best example of an implementation of the Factory design pattern. To separate an application's configuration and dependency specification from the actual application code the BeanFactory applies the Inversion of Control(IOC) pattern.

Spring AOP: - Aspect-oriented programming functionality is provided by this Spring AOP module, through its configuration management feature. There is a way through which we can easily enable AOP in any application managed by the Spring framework. The Spring AOP module provides transaction management services for objects in any Spring-based application. With the help of this Spring AOP module we can combine declarative transaction management into our applications without depending on EJB components.

Spring context: - Spring context is nothing but a configuration file that provides context information to the Spring framework. Spring context module includes enterprise services such as e-mail, internalization, validation, JNDI, EJB and scheduling functionality.

Spring DAO: - This Spring DAO module provides a meaningful exception hierarchy for managing the exception handling and error messages thrown by different database vendors. It helps in exception hierarchy for simplifying error handling. It also helps to reduce the application code we need to write, such as opening and closing connections.
Spring ORM: - This module helps to plug into several ORM frameworks to provide its Object mapping with the Relational tool, including Hibernate, JDO and iBatis SQL Maps.

Spring Web module: - This module is build on top of the application context module, providing contexts for Web-based applications. This framework supports integration with Jakarta Struts. The Web module also eases the tasks of handling multi-part requests and binding request parameters to domain objects.

Spring MVC framework: - This Spring module is full-featured MVC implementation for building Web applications. This MVC framework is highly configurable via strategy interfaces and accommodates numerous view technologies including Freemarker, JSP, Velocity, Jasper Reports, Tiles, iText, and POI.

Thursday, 8 August 2013

What is UUID(Universally Unique Identifiers)?



Generating Unique Id's

 UUID: - Universally Unique Identifiers

Question: - What is UUID?

Answer:-  A class that represents an immutable universally unique identifier (UUID). A UUID represents a 128-bit value. The UUID is generated using a cryptographically strong pseudo random number generator. A UUID is a 16-octet (128-bit) number. In its canonical form, a UUID is represented by 32 hexadecimal digits, displayed in five groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters (32 alphanumeric characters and four hyphens) or 2 128 .

For example: 550e8400-e29b-41d4-a716-446655440000

Java UUID Generator also provides a good quality UUID generator. It can generate UUID's using method 1 (MAC address + time) which is good if we need further assurance that UUID's are unique between multiple machines. It includes a JNI library to retrieve the MAC address or a mechanism to specify/generate a random MAC.

The UUID algorithm was intended to be globally unique across all time by including a network address in conjunction with a time stamp. The intent of UUIDs is to enable distributed systems to uniquely identify information without significant central coordination
UUID specification has five versions:-
  • Version 1 (MAC address) :-

Concatenation of the UUID version with the MAC address of the computer that is generating the UUID
  • Version 2 (DCE Security)

  • Version 3 (MD5 hash)

  • Version 4 (random)

  • Version 5 (SHA-1 hash)


Question:-Why UUID is required?

Answer:- Below are the cases for that we can go for UUID generation:-

  • Suppose I would like to use a cryptographically secure primary key for sensitive data in a database - this cannot be predictable and it cannot be generated by the database means I needs that key before the object is saved in the database.
  • Suppose I am working on a distributed application and during sending some data, we have to send some unique identifiers which should be unique for multiple machines.

  •  Suppose during transaction, we want to produce some unique identifiers in order to validate transactions.

  • Another typical example is the value of a cookie used as a session identifier - simply using a series of consecutive integers is generally unacceptable, since one user could easily impersonate another by altering the value of the cookie to some nearby integer.

  • Digital imaging and communication in medicine (DICOM) specifies that all DICOM objects have globally unique identifiers (UIDs). So to fulfill these scenario we can use UUID generator.

  • At last the conclusion is Some of UUID usage are for creating random file names, session id in web application, transaction id and for record’s primary keys in database replacing the sequence or auto generated number.

Famous Globally Unique Identifier generation techniques are as below:-

Technique 1 – Using UUID

When Java 5 is available, the UUID class provides a simple means for generating unique ids. The identifiers generated by UUID are actually universallyunique identifiers. 

package com.gaurav.uuid;

import java.util.UUID;

public classUUIDGeneratorFirstTechnique {

      publicstatic final void main(String... args) {
            // generate random UUIDs
            UUID generatedUniqueID = UUID.randomUUID();
            captureLogEvent(
                        "GENERATED UNIQUE IDENTIFIER IS : " + generatedUniqueID,
                        generatedUniqueID);

            finalString generatedUUIDWithoutHyphen = UUID.randomUUID().toString()
                        .replaceAll("-", "");
            System.out.println("GENERATED UUID WITHOUT HYPHEN : "
                        + generatedUUIDWithoutHyphen);
      }

      privatestatic void captureLogEvent(Object aObject, UUID uuid) {
            System.out.println(String.valueOf(aObject));
            System.out.println("GENERATED UUID VERSION       = " + uuid.version());
            System.out.println("GENERATED UUID VARIANT       = " + uuid.variant());

      }
}


Result:-

GENERATED UNIQUE IDENTIFIER IS : ec24e9b6-16e8-4075-a005-645ce224f864
GENERATED UUID VERSION       = 4
GENERATED UUID VARIANT       = 2
GENERATED UUID WITHOUT HYPHEN : 23afbb1baba54a3082bd990d979b51a8

 

Technique 2 – Using SecureRandom and MessageDigest

The following program uses SecureRandom and MessageDigest Classes to generate the UUID:
  •       During startup needs to initialize SecureRandom.
  •       when a new identifier is needed, generate a random number using SecureRandom class object
  •       create a MessageDigest class object of the random number
  •       encode the byte[] returned by the MessageDigest into some acceptable textual form
  •       check if the result is already being used ; if it is not already taken, it is suitable as a unique identifier


The MessageDigest class is suitable for generating a "one-way hash" of arbitrary data. A MessageDigest takes any input, and produces a String which :
  •       is of fixed length
  •       MessageDigest does not allow the original input to be easily recovered it's completely difficult. 
  •       MessageDigest does not uniquely identify the input,  however similar input will produce dissimilar message digests
  • MessageDigest can be used as a checksum, for verifying that data has not been altered since its creation. 



Example to generate using SecureRandom and MessageDigest

package com.gaurav.uuid;

importjava.security.MessageDigest;
importjava.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public classUUIDGeneratorSecondTechnique {
      publicstatic void main(String... args) {
            try{
                  /**

                   * Initializing SecureRandom class, This is a lengthy process so it

                   * should be initialized only upon initialization of the application

                   */

                  SecureRandom secureRandomObject = SecureRandom
                              .getInstance("SHA1PRNG");

                  /** generating a random number using SecureRandom */
                  String randomNum = new Integer(secureRandomObject.nextInt())
                              .toString();

                  /** generating a random number using MessageDigest */
                  MessageDigest messageDigestObject = MessageDigest
                              .getInstance("SHA-1");
                  byte[] resultArray = messageDigestObject.digest(randomNum
                              .getBytes());

                  System.out.println("Random number Generated Using SecureRandom object : " + randomNum);
                  System.out.println("Random number Generated Using Message digest object: " + hexadecimalEncode(resultArray));
            } catch (NoSuchAlgorithmException ex) {
                  System.err.println(ex);
            }
      }


      /**

       *

       * This converts a byte array into a String of hex characters.

       *

       */
      private staticString hexadecimalEncode(byte[] inputDataArray) {
            StringBuilder stringBuilderObject = new StringBuilder();
            char[] digitsInCharArray = { '0', '1', '2', '3', '4', '5', '6', '7',
                        '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
            for(int index = 0; index < inputDataArray.length; ++index) {
                  bytebyteData = inputDataArray[index];
                  stringBuilderObject
                              .append(digitsInCharArray[(byteData & 0xf0) >> 4]);
                  stringBuilderObject.append(digitsInCharArray[byteData & 0x0f]);
            }
            returnstringBuilderObject.toString();
      }

}

Result:-

Random number Generated Using SecureRandom object : -992077914
Random number Generated Using Message digest object: 7384973fc0e0a1c8cf6c53c27384e5e94869dfb2