Saturday, May 24, 2014

Spring Interview Questions

How do you check if the hard disk is going bad? (iostat -en, dmesg)
 What is IOC (or Dependency Injection)?
The basic concept of the Inversion of Control pattern (also known as dependency injection) is that 

  • you do not create your objects but describe how they should be created. 
  • You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file
  • A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up.

i.e., Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects. 

2. What are the different types of IOC (dependency injection) ? 
There are three types of dependency injection:
  • Constructor Injection (e.g. Pico container, Spring etc): Dependencies are provided as constructor parameters.
  • Setter Injection (e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter methods).
  • Interface Injection (e.g. Avalon): Injection is done through an interface.
  • Spring supports only constructor and setter injection


3. What are the benefits of IOC (Dependency Injection)?
Benefits of IOC (Dependency Injection) are as follows:
  • Minimizes the amount of code in your application. With IOC containers you do not care about how services are created and how you get references to the ones you need. You can also easily add additional services by adding a new constructor or a setter method with little or no extra configuration.
  • Make your application more testable by not requiring any singletons or JNDI lookup mechanisms in your unit test cases. IOC containers make unit testing and switching implementations very easy by manually allowing you to inject your own objects into the object under test.
  • Loose coupling is promoted with minimal effort and least intrusive mechanism. The factory design pattern is more intrusive because components or services need to be requested explicitly whereas in IOC the dependency is injected into requesting piece of code.
    Also some containers promote the design to interfaces not to implementations design concept by encouraging managed objects to implement a well-defined service interface of your own.
  • IOC containers support eager instantiation and lazy loading of services. Containers also provide support for instantiation of managed objects, cyclical dependencies, life cycles management, and dependency resolution between managed objects etc

What is Spring ?
  • Spring is an open source framework created to address the complexity of enterprise application development. 
  • One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use while also providing a cohesive framework for J2EE application development.

What are the advantages of Spring framework?
The advantages of Spring are as follows:
  • Spring has layered architecture. Use what you need and leave you don't need now.
  • Spring Enables POJO Programming. There is no behind the scene magic here. POJO programming enables continuous integration and testability.
  • Dependency Injection and Inversion of Control Simplifies JDBC
  • Open source and no vendor lock-in.


6. What are features of Spring ?
  • spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 1MB. And the processing overhead is also very negligible.
  • Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects.
  • Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services.
  • Spring contains and manages the life cycle and configuration of application objects.
  • Spring comes with MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI. But other frameworks can be easily used instead of Spring MVC Framework.
  • Spring framework provides a generic abstraction layer for transaction management. This allowing the developer to add the pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. Spring's transaction support is not tied to J2EE environments and it can be also used in container less environments.
  • The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the error handling strategy. Integration with Hibernate, JDO, and iBATIS: Spring provides best Integration services with Hibernate, JDO and iBATIS


7. How many modules are there in Spring? What are they?
(Roll over to view the Image )
Spring Framework Modules
       Spring comprises of seven modules. They are..
  • The core container provides the essential functionality of the Spring framework. A primary component of the core container is the BeanFactory, an implementation of the Factory pattern. The BeanFactory applies the Inversion of Control (IOC) pattern to separate an application's configuration and dependency specification from the actual application code.

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

  • The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework, through its configuration management feature. As a result you can easily AOP-enable any object managed by the Spring framework. The Spring AOP module provides transaction management services for objects in any Spring-based application. With Spring AOP you can incorporate declarative transaction management into your applications without relying on EJB components.

  • The Spring JDBC DAO abstraction layer offers a meaningful exception hierarchy for managing the exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of exception code you need to write, such as opening and closing connections. Spring DAO's JDBC-oriented exceptions comply to its generic DAO exception hierarchy.

  • The Spring framework plugs into several ORM frameworks to provide its Object Relational tool, including JDO, Hibernate, and iBatis SQL Maps. All of these comply to Spring's generic transaction and DAO exception hierarchies.

  • The Web context module builds on top of the application context module, providing contexts for Web-based applications. As a result, the Spring 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.

  • The Model-View-Controller (MVC) framework is a full-featured MVC implementation for building Web applications. The MVC framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP, Velocity, Tiles, iText, and POI.



8. What are the types of Dependency Injection Spring supports?>
  • Setter-based DI is realized by calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.

  • Constructor-based DI is realized by invoking a constructor with a number of arguments, each representing a collaborator.



9. What is Bean Factory ?
A BeanFactory is like a factory class that contains a collection of beans. The BeanFactory holds Bean Definitions of multiple beans within itself and then instantiates the bean whenever asked for by clients.
  • BeanFactory is able to create associations between collaborating objects as they are instantiated. This removes the burden of configuration from bean itself and the beans client.
  • BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.

10. What is Application Context?
A bean factory is fine to simple applications, but to take advantage of the full power of the Spring framework, you may want to move up to Springs more advanced container, the application context. On the surface, an application context is same as a bean factory.Both load bean definitions, wire beans together, and dispense beans upon request. But it also provides:
  • A means for resolving text messages, including support for internationalization.
  • A generic way to load file resources.
  • Events to beans that are registered as listeners.

11. What is the difference between Bean Factory and Application Context ?  
On the surface, an application context is same as a bean factory. But application context offers much more..
  • Application contexts provide a means for resolving text messages, including support for i18n of those messages.

  • Application contexts provide a generic way to load file resources, such as images.

  • Application contexts can publish events to beans that are registered as listeners.

  • Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context.

  • ResourceLoader support: Spring’s Resource interface us a flexible generic abstraction for handling low-level resources. An application context itself is a ResourceLoader, Hence provides an application with access to deployment-specific Resource instances.

  • MessageSource support: The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable


http://www.developersbook.com/spring/interview-questions/spring-interview-questions-faqs-2.php

Saturday, May 3, 2014

Annotations in Java

Why, how, where and when for Annotations


Annotations are meta-meta-object which can be used to describe other meta-object. Meta-object are class, field and method. Asking an object for its meta-object (e.g. anObj.getClass() ) is calledintrospection. The introspection can go further and we can ask a meta-object what are its annotations (e.g. aClass.getAnnotations). Introspection and annotations belong to what is called reflexion andmeta-programming.
An annotation needs to be interpreted in one way or another to to be useful. Annotations can be interpreted at development-time by the IDE or the compiler or at run-time by a framework.
Annotation is a very powerful mechanism and can be used in a lot of different ways:
  • to describe constraints or usage of an element: e.g. @Deprecated, @Override, or @NotNull
  • to describe the "nature" of an element, e.g. @Entity, @TestCase, @WebService
  • to describe the behavior of an element: @Statefull, @Transaction
  • to describe how to process the element: @Column, @XmlElement
In all case, an annotation is used to describe the element, which is frequently referred as its semantics.
Prior to JDK5, the information that is now contained in the annotations needed to be stored somewhere else, and XML files were frequently used. But it is more convenient to use annotations because they will belong to the Java code itself, and are hence much easier to manipulate than XML.
Usage of annotations:
  • Documentation, e.g. XDoclet
  • Compilation
  • IDE
  • Testing framework, e.g. JUnit
  • IoC container e.g. as Spring
  • Serialization, e.g. XML
  • Aspect-oriented programming (AOP), e.g. Spring AOP
  • Application servers, e.g. EJB container, Web Service
  • Object-relational mapping (ORM), e.g. Hibernate, JPA
  • and many more...
...have a look for instance at project Lombok, which uses annotation to define how to generate equalsor hashCode methods.

Saturday, November 10, 2012

GOF : Creational 1. Factory Method Design pattern


What is a factory?

  • factory is an object for creating other objects. 
  • It is an abstraction of a constructor, and 
  • can be used to implement various allocation schemes. For example, using this definition, singletons implemented by the singleton pattern are formal factories.
  • A factory object typically has a method for every kind of object it is capable of creating. These methods optionally accept parameters defining how the object is created, and then return the created object.
  • Advance Use: The factory object might decide to create the object's class (if applicable) dynamically, return it from an object pool, do complex configuration on the object, or other things.
  • These kinds of objects have proven useful and several design patterns have been developed to implement them in many languages. For example, several "GoF patterns", like the "Factory method pattern", the "Builder" or even the "Singleton" are implementations of this concept. The "Abstract factory pattern" instead is a method to build collections of factories.
  • Factory objects are common in toolkits and frameworks where library code needs to create objects of types which may be subclassed by applications using the framework. They are also used in test-driven development to allow classes to be put under test.

Use of factory : Where and When

  • Factories determine the actual concrete type of object to be created, 
  • it is here that the object is actually created
  • As the factory only returns an abstract pointer, the client code does not know - and is not burdened by - the actual concrete type of the object which was just created. However, the type of a concrete object is known by the abstract factory. In particular, this means:

  • The client code has no knowledge whatsoever of the concrete type, so it does not need to include any header files or class declarations relating to the concrete type. 
  • The client code deals only with the abstract type. 
  • Objects of a concrete type are indeed created by the factory, but the client code accesses such objects only through their abstract interface.
  • Adding new concrete types is done by modifying the client code to use a different factory, a modification which is typically one line in one file. This is significantly easier than modifying the client code to instantiate a new type, which would require changing every location in the code where a new object is created.

Factory method Pattern 

Factory methods are static methods that return an instance of the native class. Examples in the JDK include :
Factory methods :
  • have names, unlike constructors, which can clarify code.
  • do not need to create a new object upon each invocation - objects can be cached and reused, if necessary.
  • can return a subtype of their return type - in particular, can return an object whose implementation class is unknown to the caller. This is a very valuable and widely used feature in many frameworks which use interfaces as the return type of static factory methods.
  • The creation of an object requires access to information or resources that should not be contained within the composing class
  • Common names for factory methods include getInstance and valueOf. These names are not mandatory - choose whatever makes sense for each case.
  • When factory methods are used for disambiguation like this, the constructor is often made private to force clients to use the factory methods.
  • Factory methods encapsulate the creation of objects. This can be useful, if the creation process is very complex; for example, if it depends on settings in configuration files or on user input.


public class Complex
    {
        public double real;
        public double imaginary;
 
        public static Complex FromCartesianFactory(double real, double imaginary ) 
        {
            return new Complex(real, imaginary);
        }
 
        public static Complex FromPolarFactory(double modulus , double angle ) 
        {
            return new Complex(modulus * Math.Cos(angle), modulus * Math.Sin(angle));
        }
 
 
        private Complex (double real, double imaginary)
        {
            this.real = real;
            this.imaginary = imaginary;
        }
    }
 
Complex product = Complex.FromPolarFactory(1,pi);


public class ComplexNumber {

  /**
  * Static factory method returns an object of this class.
  */
  public static ComplexNumber valueOf(float aReal, float aImaginary) {
    return new ComplexNumber(aReal, aImaginary);
  }

  /**
  * Caller cannot see this private constructor.
  *
  * The only way to build a ComplexNumber is by calling the static 
  * factory method.
  */
  private ComplexNumber (float aReal, float aImaginary) {
    fReal = aReal;
    fImaginary = aImaginary;
  }

  private float fReal;
  private float fImaginary;

  //..elided
} 

Limitations

There are three limitations associated with the use of the factory method. The first relates to refactoring existing code; the other two relate to extending a class.
  • The first limitation is that refactoring an existing class to use factories breaks existing clients. For example, if class Complex were a standard class, it might have numerous clients with code like:
Complex c = new Complex(-1, 0);
Once we realize that two different factories are needed, we change the class (to the code shown earlier). But since the constructor is now private, the existing client code no longer compiles.
  • The second limitation is that, since the pattern relies on using a private constructor, the class cannot be extended. Any subclass must invoke the inherited constructor, but this cannot be done if that constructor is private.
  • The third limitation is that, if we do extend the class (e.g., by making the constructor protected—this is risky but feasible), the subclass must provide its own re-implementation of all factory methods with exactly the same signatures. For example, if class StrangeComplex extends Complex, then unless StrangeComplex provides its own version of all factory methods, the call
    StrangeComplex.fromPolar(1, pi);
    
    will yield an instance of Complex (the superclass) rather than the expected instance of the subclass. The reflection features of some languages can obviate this issue.
All three problems could be alleviated by altering the underlying programming language to make factories first-class class members (see also Virtual class).[4]

      Thursday, November 8, 2012

      Quickies for Quick Results : Jar and JUnit

      1.Updating a Jar File

      The Jar tool provides a u option which you can use to update the contents of an existing JAR file by modifying its manifest or by adding files.

      The basic command for adding files has this format:
      jar uf jar-file input-file(s)
      
      In this command:
      • The u option indicates that you want to update an existing JAR file.
      • The f option indicates that the JAR file to update is specified on the command line.
      • jar-file is the existing JAR file that's to be updated.
      • input-file(s) is a space-deliminated list of one or more files that you want to add to the Jar file.
      Also, please remember the following before executing the command :
      • Any files already in the archive having the same pathname as a file being added will be overwritten.
      • When creating a new JAR file, you can optionally use the -C option to indicate a change of directory
      If using windows command line put the "class file" ( which you want to replace in the jar file ), in the same directory hierarchy as that of the file in the jar file. Otherwise the file would be either added to some other location or will not appear at all.

      Also, Use Zip or 7-zip software to look into the jar file. This will help you to
      • Obtain the fully qualified name of the class file you want to replace. ( using it you will create the folder structure (eg org/apache/hadoop/mapred/abc.class) that you want to create for the file).
      • After jar command execution you can recheck the timestamp of the file in the new jar file. If it is an old one you need to replace it with a new one.
      • For more info
      2. Running tests using junit (Testcase) :

      If you have your test case file in a jar file use the option from following depending on your JUnit's version.
      test class name is the fully qualified name of your test class file.
      For JUnit 4.X it's really:
      java -cp /usr/share/java/junit.jar:{any other jar files/ your jar file where your test case resides} org.junit.runner.JUnitCore [test class name]
      
      But if you are using JUnit 3.X please note the class name is different:
      java -cp /usr/share/java/junit.jar:{any other jar files/ your jar file where your test case resides} junit.textui.TestRunner [test class name]

      Hadoop Releases, Projects and features in a nutshell

      Hadoop Features in HDFS and MR across releases



      News on releases : Oct 2012 : 

      9 October, 2012: Release 2.0.2-alpha available

      This is the second (alpha) version in the hadoop-2.x series.
      This delivers significant enhancements to HDFS HA. Also it has a significantly more stable version of YARN which, at the time of release, has already been deployed on a 2000 node cluster.
      Please see the Hadoop 2.0.2-alpha Release Notes for details.
      Latest Hadoop : http://hadoop.apache.org/docs/current/ : 2.0.2
      Latest Stable Release : http://hadoop.apache.org/docs/stable/ : 1.0.4

      Common
      A set of components and interfaces for distributed filesystems and general I/O
      (serialization, Java RPC, persistent data structures).


      Avro
      A serialization system for efficient, cross-language RPC and persistent data
      storage.

      MapReduce
      A distributed data processing model and execution environment that runs on large
      clusters of commodity machines.

      HDFS
      A distributed filesystem that runs on large clusters of commodity machines.

      Pig
      A data flow language and execution environment for exploring very large datasets.
      Pig runs on HDFS and MapReduce clusters.

      Hive
      A distributed data warehouse. Hive manages data stored in HDFS and provides a
      query language based on SQL (and which is translated by the run time engine to
      MapReduce jobs) for querying the data.

      HBase
      A distributed, column-oriented database. HBase uses HDFS for its underlying
      storage, and supports both batch-style computations using MapReduce and point
      queries (random reads).

      ZooKeeper
      A distributed, highly available coordination service. ZooKeeper provides primitives
      such as distributed locks that can be used for building distributed applications.


      Sqoop
      A tool for efficient bulk transfer of data between structured data stores (such as
      relational databases) and HDFS.

      Oozie
      A service for running and scheduling workflows of Hadoop jobs (including Map-
      Reduce, Pig, Hive, and Sqoop jobs).

      Note referenece : Hadoop The Definitive GUIDE (3rd Edition) & Hadoop 

      2. SQL statements interview questions: a must know list

      The JOIN concept
      JOIN is a query clause that can be used with the SELECT, UPDATE, and DELETE data query statements to simultaneously affect rows from multiple tables. There are several distinct types of JOIN statements that return different data result sets.

      Joined tables must each include at least one field in both tables that contain comparable data. For example, if you want to join a Customer table and a Transaction table, they both must contain a common element, such as a CustomerID column, to serve as a key on which the data can be matched. Tables can be joined on multiple columns so long as the columns have the potential to supply matching information. Column names across tables don't have to be the same, although for readability this standard is generally preferred.

      Now that we’ve examined the basic theory, let’s take a look at the various types of joins and examples of each.

      The basic JOIN statement
      A basic JOIN statement has the following format:
      SELECT Customer.CustomerID, TransID, TransAmt
      FROM Customer JOIN Transaction
      ON Customer.CustomerID = Transaction.CustomerID;


      In practice, you'd never use the example above because the type of join is not specified. In this case, SQL Server assumes an INNER JOIN. You can get the equivalent to this query by using the statement:
      SELECT Customer.CustomerID, TransID, TransAmt
      FROM Customer, Transaction;

      However, the example is useful to point out a few noteworthy concepts:
      • TransID and TransAmt do not require fully qualified names because they exist in only one of the tables. You can use fully qualified names for readability if you wish.
      • The Customer table is considered to be the “left” table because it was called first. Likewise, theTransaction table is the “right” table.
      • You can use more than two tables, in which case each one is “naturally” joined to the cumulative result in the order they are listed, unless controlled by other functionality such as “join hints” or parenthesis.
      • You may use WHERE and ORDER BY clauses with any JOIN statement to limit the scope of your results. Note that these clauses are applied to the results of your JOIN statement.
      • SQL Server does not recognize the semicolon (;), but I use it in the included examples to denote the end of each statement, as would be expected by most other RDBMSs.
      The INNER JOIN drops rows
      When you perform an INNER JOIN, only rows that match up are returned. Any time a row from either table doesn’t have corresponding values from the other table, it is disregarded. Because stray rows aren’t included, you don’t have any of the “left” and “right” nonsense to deal with and the order in which you present tables matters only if you have more than two to compare. Since this is a simple concept, here’s a simple example:

      SELECT CustomerName, TransDate
      FROM Customer INNER JOIN Transaction
      ON Customer.CustomerID = Transaction.CustomerID;


      If a row in the Transaction table contains a CustomerID that’s not listed in the Customer table, that row will not be returned as part of the result set. Likewise, if the Customer table has a CustomerIDwith no corresponding rows in the Transaction table, the row from the Customer table won’t be returned.


      The OUTER JOIN can include mismatched rows
      OUTER JOINs, sometimes called “complex joins,” aren’t actually complicated. They are so-called because SQL Server performs two functions for each OUTER JOIN.

      The first function performed is an INNER JOIN. The second function includes the rows that the INNER JOIN would have dropped. Which rows are included depends on the type of OUTER JOIN that is used and the order the tables were presented.

      There are three types of an OUTER JOIN: LEFT, RIGHT, and FULL. As you’ve probably guessed, the LEFT OUTER JOIN keeps the stray rows from the “left” table (the one listed first in your query statement). In the result set, columns from the other table that have no corresponding data are filled with NULL values. Similarly, the RIGHT OUTER JOIN keeps stray rows from the right table, filling columns from the left table with NULL values. The FULL OUTER JOIN keeps all stray rows as part of the result set. Here is your example:
      SELECT CustomerName, TransDate, TransAmt
      FROM Customer LEFT OUTER JOIN Transaction
      ON Customer.CustomerID = Transaction.CustomerID;

      Customer names that have no associated transactions will still be displayed. However, transactions with no corresponding customers will not, because we used a LEFT OUTER JOIN and theCustomer table was listed first.

      In SQL Server, the word OUTER is actually optional. The clauses LEFT JOIN, RIGHT JOIN, and FULL JOIN are equivalent to LEFT OUTER JOIN, RIGHT OUTER JOIN, and FULL OUTER JOIN, respectively.

      1. SQL statements interview questions: a must know list


      1. you will want to list only the different (distinct) values in a table.
      The DISTINCT keyword can be used to return only distinct (different) values.

      SQL SELECT DISTINCT Syntax

      SELECT DISTINCT column_name(s)
      FROM table_name

      2. SQL UNIQUE Constraint
      The UNIQUE constraint uniquely identifies each record in a database table.
      The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns.
      A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.
      Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.

      SQL UNIQUE Constraint on CREATE TABLE

      The following SQL creates a UNIQUE constraint on the "P_Id" column when the "Persons" table is created:
      MySQL:
      CREATE TABLE Persons
      (
      P_Id int NOT NULL,
      LastName varchar(255) NOT NULL,
      FirstName varchar(255),
      Address varchar(255),
      City varchar(255),
      CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)
      )

      ALTER TABLE Persons
      ADD CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)


      3. The ORDER BY Keyword

      The ORDER BY keyword is used to sort the result-set by a specified column.
      The ORDER BY keyword sorts the records in ascending order by default.
      If you want to sort the records in a descending order, you can use the DESC keyword.

      SQL ORDER BY Syntax

      SELECT column_name(s)
      FROM table_name
      ORDER BY column_name(s) ASC|DESC

      SELECT * FROM Persons
      ORDER BY LastName


      4. The LIKE Operator
      The LIKE operator is used to search for a specified pattern in a column.

      The "Persons" table:
      P_IdLastNameFirstNameAddressCity
      1HansenOlaTimoteivn 10Sandnes
      2SvendsonToveBorgvn 23Sandnes
      3PettersenKariStorgt 20Stavanger


      We use the following SELECT statement:
      SELECT * FROM Persons
      WHERE City LIKE '%s'
      The result-set will look like this:
      P_IdLastNameFirstNameAddressCity
      1HansenOlaTimoteivn 10Sandnes
      2SvendsonToveBorgvn 23Sandnes



      We use the following SELECT statement:
      SELECT * FROM Persons
      WHERE City LIKE '%tav%'
      The result-set will look like this:
      P_IdLastNameFirstNameAddressCity
      3PettersenKariStorgt 20Stavanger



      It is also possible to select the persons living in a city that does NOT contain the pattern "tav" from the "Persons" table, by using the NOT keyword.
      We use the following SELECT statement:
      SELECT * FROM Persons
      WHERE City NOT LIKE '%tav%'
      The result-set will look like this:
      P_IdLastNameFirstNameAddressCity
      1HansenOlaTimoteivn 10Sandnes
      2SvendsonToveBorgvn 23Sandnes