Its very easy to remove unnecessary imports and characters while saving a file in eclipse.This will help to avoid sonar issues in our code base.

go to eclipse-> preferences->Java -> Editor->Save Actions and give the below checkbox options as looks in picture below.




also do the advanced level setting by clicking configure button













Lets assume we want to go to a trip to Paris.What we will do ? You have to plan everything

1) Book your flights
2)Book your hotels to stay
3)Book your car rental for travelling in Paris
4)Book your amenity pass for visiting different places

assume that you have done all the booking advance and there is an email from flight authority that the flight scheduled is cancelled and it is rescheduled to next day. What you will do?

you have to reschedule all the above bookings to next day and to communicate all the different agencies(hotel/car rental/amenity pass center). This is a pain for you by this unexpected channges happened right?  Now think about a situation that your booking is done by a travel agency including 
all the booking and because of flight delay they rescheduled everything by themself without charging
any extra dollar from you and you will be able to travel on the same day without any delay !!

How it will feel ? nice right. You dont bother about the rescheduling and re booking of all your tickets, travel agency will take care of everything. Would that be better than booking tickets by ourselves? If yes, then welcome to dependency injection.


The whole example is easily clonable or download from GitHub repository

Dependency injection is a framework that takes care of creating objects for us without having to worry about providing the right tickets so to say.

Explanation

Consider we have a class Student and this class need to write a test need help on another class WriteTest() which will help us to write a test for a student.
   package com.johnjustin;

public class AttendExam {
 
 public void writeTest(final String ExamName, final String subject) {
     System.out.printf("writeTest : %s, %s%n", ExamName, subject);
   }

}

package com.johnjustin;

public class Student {
  private AttendExam attendExam = new AttendExam();

  public void writeTest(){
    attendExam.writeTest("Engineering", "Mathematics");
  }
}


This is the simplest way to fulfill the requirement but we know that this has some limitations

1)There is a tight dependency on AttendExam class on Student class.
2) if there is a design change planned on writeTest() method with different parameters and there might be changes happened for different types of exams like online exam and offline written exam
we should go to all the places wherever this AttendExam written will be changed.
3)After sometimes there is new requirement came and we have to implement 2 types of tests.Online assessment and offline written test at this scenario it will be difficult for us to maintain same AttendExam class.
These limitations can be improved by changing the way we think and refactor our code in a modular way.We can avoid these limitations by implementing dependency injection by modular way.


1)Create Interface
2)Implement Interface
3)integrate DI using any(Spring/Guice) framework

these three steps will help to decouple the tight dependencies between classes and it will be easy to migrate newer version of changes and updation of existing features without changing the current codes.

Create Interface

We will create an interface AssessmentService where we define a common method writeTest with parameters.So there must be different types of test either online test or written test both classes will inherit this AssessmentService and implement writeTest for their own exam implementation.
package com.johnjustin;

public interface AssessmentService {
 
 void writeTest(String subject, String testName);

}

Implement Interfaces

We have listed some limitations above and there is requirement to implement 2 types of tests online assessment and offline written tests. We have created 2 different classes OnlineExamService and WrittenExamService for these tests and it will inherit the feature of AssessmentService interface's writeTest method.
    package com.johnjustin;

/**
 * @author John Justin
 *
 */
public class WrittenExamService implements AssessmentService{
 
 public void writeTest(final String ExamName, final String subject) {
     System.out.printf("Written Exam for : %s, %s%n", ExamName, subject);
   }


}
    package com.johnjustin;

/**
 * @author John Justin
 *
 */
public class OnlineExamService implements AssessmentService{
 
 public void writeTest(final String ExamName, final String subject) {
     System.out.printf("Online Exam for : %s, %s%n", ExamName, subject);
   }

}
Use interfaces to reduce loosely couple the classes. We have to use this AssessmentService in our Student class and implement required type of assessment(Online/Written) according to the need.This is a key element in the design. It improves modularity, extendibility.
  
     package com.johnjustin;
import com.johnjustin.AssessmentService;
import com.google.inject.Inject;

/**
 * @author John Justin
 *
 */
public class Student {

 private final AssessmentService assessmentService;
 
 @Inject
 private Student(AssessmentService assessmentService){
  
  this.assessmentService = assessmentService;
 } 
 
 public void attendExam() {
   assessmentService.writeTest("Engineering", "Mathematics");
    }
  
 
}

 
The Student class is not dependent on any implementation, but on a service defined by an interface. This means that we can use the Student class without having to worry about the underlying implementation of the assessment service. Furthermore, different Student instances can be instantiated using different assessment services.

Integrate DI using any(Spring/Guice) framework


dependency injection can help us initializing objects and provide these objects all the necessary resources . For example, the Student class requires an instance of AssessmentService. The dependency injection framework( Guice here) will provide that for us. So to create an instance of Student class.

The dependency injection framework(Guice) will create an instance of the Student class and provide an instance of the AssessmentServiceto the Student object.

How to integrate google Guice dependency frame work in our programe?
how does the dependency injection framework knows how to initialise the AssessmentService?

Usage of Dependency Injection requires that the software we write to declare the dependencies, and lets the framework or the container work out the complexities of service instantiation, initialization, sequencing and supplies the service references to the clients as required. To decouple Java components from other Java components the dependency to a certain other class should get injected into them rather that the class itself creates / finds this object.    

The general concept between dependency injection is called Inversion of Control. A class should not configure itself but should be configured from outside.          

 We need to tell the dependency injection framework how to create an instance of AssessmentService. With Guice we do that by creating a module (a class that extends AbstractModule class) as illustrated below. 

We should tell the Guice dependency framework to how to create an instance of AssessmentService class.We should add an annotation in Student class in order to allow the dependency injection framework to inject the necessary parameters.
 
     package com.johnjustin;

import com.google.inject.AbstractModule;

/**
 * @author John Justin
 *
 */
public class ProjectModule extends AbstractModule {
 
 @Override
   protected void configure() {
     bind(AssessmentService.class).to(OnlineExamService.class);
   }

}
        package com.johnjustin;
import com.johnjustin.AssessmentService;
import com.google.inject.Inject;

/**
 * @author John Justin
 *
 */
public class Student {

 private final AssessmentService assessmentService;
 
 @Inject
 private Student(AssessmentService assessmentService){
  
  this.assessmentService = assessmentService;
 } 
 
 public void attendExam() {
   assessmentService.writeTest("Engineering", "Mathematics");
    }
  
 
}
Now we can create the main class and create its injection in it.
package com.johnjustin;

import com.google.inject.Guice;
import com.google.inject.Injector;

/**
 * @author  John Justin
 *
 */
public class Main {
 
 
  public static void main(final String[] args) {
      final Injector injector = Guice.createInjector(new ProjectModule());
      final Student student = injector.getInstance(Student.class);
      student.attendExam();
    }

}

Advantages of DI


Dependency injection is a pattern used to create instances of classes that other classes rely on without knowing at compile time which implementation will be used to provide that functionality.

Easily changing the the exam type from online exam service to written exam service.We only need to change the ProjectModule class to map the AssessmentService class to the WrittenExamService class as highlighted below.This one change will affect all classes initialised with the dependency injection framework without having to change any of these classes.
package com.johnjustin;

import com.google.inject.AbstractModule;

/**
 * @author John Justin
 *
 */
public class ProjectModule extends AbstractModule {
 
 @Override
   protected void configure() {
     bind(AssessmentService.class).to(WrittenExamService.class);
   }

}

The whole example is easily clonable or download from GitHub repository.Enjoy !!!!!






In your collection implementation how you will make sure the unique values without implementing set/hashSet interface? otherway how you implement set interface in your java collection data?

For example


public class Test {
    
    public static void main(String[] args)
    {
       
        HashSet<Object> testSet= new HashSet<Object>();
        testSet.add(100);
        testSet.add("hello");
        System.out.println("Result "+testSet);
    }
}

The result will be : Result [100, hello ] 

Now we will add some duplicate elements in the same collection list


public class Test {
    
    public static void main(String[] args)
    {
       
        HashSet<Object> testSet= new HashSet<Object>();
        testSet.add(100);
        testSet.add("hello");
        testSet.add(100);
        testSet.add("hello");
System.out.println("Result "+testSet); } }

The result will be : Result [100, hello ] 

Eventhough when we add duplicate element in this collection set with add method why the duplicated data not inserted? because add method returs false when we try to add duplicate elements. How the add method returns false?
The HashSet implementation of the add() method in java is internally implemented by HashMap implementation.

Whenever we tries to create an object of HashSet , it internally create an object of HashMap 

public class HashSet
extends AbstractSet
implements Set, Cloneable, java.io.Serializable

{
    private transient HashMap map;
           
    private static final Object PRESENT = new Object();
        
                public HashSet() {
                      map = new HashMap<>();
                    }
    
       
               public boolean add(E e) {
                       return map.put(e, PRESENT)==null;
                   }
    
       

}


The key is unique in hashmap , when we are calling add(Element E) this element E will be added as key in HashMap and the value for key will be added by the java developer api by using the variable PRESENT , it will create ( new Object() ) which is a dummy value referred by Object reference PRESENT

when you are adding a line in HashSet like  hashset.add(100)   what java does internally is that it will put that element E here 100 as a key in the HashMap(created during HashSet object creation) and some dummy value that is Object's object is passed as a value to the key .

The main point to notice in above code is that put (key,value) will return

1.  null , if key is unique and added to the map
2.  Old Value of the key , if key is duplicate

So , in HashSet add() method ,  we check the return value of map.put(key,value) method with null value
i.e.

   public boolean add(E e) {
            return map.put(e, PRESENT)==null;
       }

So , if map.put(key,value) returns null ,then
map.put(e, PRESENT)==null      will return true and element is added to the HashSet.

So , if map.put(key,value) returns old value of the key ,then
map.put(e, PRESENT)==null      will return false and element is  not added to the HashSet .

What is a Collection? 
• An object that groups multiple elements into a single unit.
 • Sometimes called a container






     img courtesy - http://javahungry.blogspot.com/

There are two ways to traverse collections:
1) using Iterators.
2) with the (enhanced) for-each construct

Iterators 

• An Iterator is an object that enables you to traverse through a collection and to remove elements from the collection selectively, if desired.

• You get an Iterator for a collection by calling its iterator method.

• Suppose collection is an instance of a Collection. Then to print out each element on a separate line:

Iterator it = collection.iterator(); 
while (it.hasNext())
 System.out.println(it.next());

 • Note that next() does two things:
                    1. Returns the current element (initially the first element)
                    2. Steps to the next element and makes it the current element. 



    Levels of Abstraction 

• Recall that Java supports three levels of abstraction: –

 - Interface 

             • Java expression of an ADT
             • Includes method declarations with arguments of specified types, but with empty bodies


 – Abstract Class 

             • Implements only a subset of an interface.
             • Cannot be used to instantiate an object. 


– (Concrete) Classes 

            • May extend one or more abstract classes
            • Must fully implement any interface it implements 
            • Can be used to instantiate objects. 


Iterating Over a Map 

• Because Map does not extend Iterable, but Collection (hence Set) does extend Iterable, you can (only) iterate over a Map using one of its three views:
           – Keys: Set keySet() 
           – Values: Collection values() 
           – Pairs: Set> entrySet()


 What is the root interface in collection hierarchy ? 

Root interface in collection hierarchy is Collection interface . Few interviewer may argue that 
Collection interface extends Iterable interface. So iterable should be the root interface. But you should reply iterable interface present in java.lang package not in java.util package .It is clearly mentioned in Oracle Collection  docs , that Collection interface is a member of the Java Collections framework.  For Iterable interface Oracle doc , iterable interface is not mentioned as a part of the Java Collections framework .So if the question includes  collection hierarchy , then you should answer the question as Collection interface (which is found in java.util package).

 What is the difference between Collection and Collections ?

Collection is  an interface while Collections is a java class , both are present in java.util package and  part of java collections framework.

 Which collection classes are synchronized or thread-safe ?

Stack, Properties , Vector and Hashtable can be used in multi threaded environment because they are synchronized classes (or thread-safe). 
Camel Book in one page

  Camel books Camel in action


 It enables easy integration of different applications which use several protocols and technologies.Synchronous remote procedure calls or asynchronous messaging is used to communicate via several technologies such as RMI, SOAP Web Services, REST or JMS. A lot of software silos exists. Nevertheless, all applications and products of these decades have to communicate with each other to work together perfectly.

What is Apache Camel?
Apache Camel is a lightweight integration framework which implements all EIPs. Thus, you can easily integrate different applications using the required patterns. You can use Java, Spring XML, Scala or Groovy. Almost every technology you can imagine is available, for example HTTP, FTP, JMS, EJB, JPA, RMI, JMS, JMX, LDAP, Netty, and many, many more (of course most ESBs also offer support for them). Besides, own custom components can be created very easily.
You can deploy Apache Camel as standalone application, in a web container (e.g. Tomcat or Jetty), in a JEE application Server (e.g. JBoss AS or WebSphere AS), in an OSGi environment or in combination with a Spring container.
If you need more information about Apache Camel, please go to its web site as starting point: http://camel.apache.org. This article is no technical introduction J
When to use Apache Camel?
Apache Camel is awesome if you want to integrate several applications with different protocols and technologies. Why? There is one feature (besides supporting so many technologies and besides supporting different programming languages)  Every integration uses the same concepts! No matter which protocol you use. No matter which technology you use. No matter which domain specific language (DSL) you use – it can be Java, Scala, Groovy or Spring XML. You do it the same way. Always! There is a producer, there is a consumer, there are endpoints, there are EIPs, there are custom processors / beans (e.g. for custom transformation) and there are parameters (e.g. for credentials).

 What is the difference between enrich() and pollEnrich()?

  Content enricher here  ( Link)

 Content enrichment using the enrich DSL element Camel comes with two flavors of content enricher in the DSL enrich pollEnrich enrich uses a Producer to obtain the additional data. It is usually used for Request Reply messaging, for instance to invoke an external web service. pollEnrich on the other hand uses a Polling Consumer to obtain the additional data. It is usually used for Event Message messaging, for instance to read a file or download a FTP file.

  • enrich assumes you want to use an incoming Exchange as a parameter to an another service request. for example, your incoming Exchange could be a userID, but you really need the entire User object, so you could enrich it by passing the userID to a REST service that returns the User object which becomes the Exchange, etc.
  • pollEnrich assumes the incoming Exchange is a simple trigger that tell a PollingConsumer to look for data and create an Exchange (ignoring the contents of the incoming Exchange). For example, you could have a timer or other business process event that requires picking up a file for processing, etc. that said, the incoming Exchange data is NOT used to dynamically configure the PollingConsumer...only the URI is used for this.
What are different message exchange patterns in Camel, which one of these is synchronous?
A: There are two types of message exchange patterns in Camel:
  • In Only: In this exchange pattern, consumer creates a exchange which only contains an In message.
  • In Out: In this exchange pattern, consumer creates a exchange which also contains reply message for the caller.
Out of above two, InOut pattern is synchronous because caller expects for an acknowledgement or reply for each exchange sent.

What is camel exchange? Explain its structure?
A: A Camel Exchange can be called as an holder for holding message during routing. A exchange supports various message exchange patterns, like InOnly and InOut.
Following are the contents of camel exchange:
  • ExchangeId: A unique identifier for each exchange
  • Message Exchange Pattern: This field denotes whether you are using InOnly or InOut exchange pattern.
  • Exception: If any exception occurs during routing, it will be available in this field.
  • Properties: These are the properties that are available for entire duration of exchange.
  • In Message: This is mandatory field which contains the input message.
  • Out Message: This is optional message which exists only if MEP is InOut.