Monday, February 20, 2012

Java Spring and Hibernate Interview Questions

1. Explain DI or IOC pattern. 

Dependency injection (DI) is a programming design pattern and architectural model, sometimes also referred to as inversion of control or IOC, although technically speaking, dependency injection specifically refers to an implementation of a particular form of IOC. Dependency Injection describes the situation where one object uses a second object to provide a particular capacity. For example, being passed a database connection as an argument to the constructor method instead of creating one inside the constructor. The term "Dependency injection" is a misnomer, since it is not a dependency that is injected; rather it is a provider of some capability or resource that is injected. There are three common forms of dependency injection: setter, constructor and interface-based injection. 

Dependency injection is a way to achieve loose coupling. Inversion of control (IOC) relates to the way in which an object obtains references to its dependencies. This is often done by a lookup method. The advantage of inversion of control is that it decouples objects from specific lookup mechanisms and implementations of the objects it depends on. As a result, more flexibility is obtained for production applications as well as for testing.


2. What are the different IOC containers available?

Spring is an IOC container. Other IOC containers are HiveMind, Avalon, PicoContainer.

3. What are the different types of dependency injection? Explain with examples.


There are two types of dependency injection: setter injection and constructor injection.
Setter Injection: Normally in all the java beans, we will use setter and getter method to set and get the value of property as follows:

public class namebean {
String name;
public void setName(String a) {
name = a; }
public String getName() {
return name; }
}

We will create an instance of the bean 'namebean' (say bean1) and set property as bean1.setName("tom"); Here in setter injection, we will set the property 'name' in spring configuration file as shown below:

< bean id="bean1" class="namebean" >
< property name="name" >
< value > tom < / value >
< / property >
< / bean >

The subelement < value > sets the 'name' property by calling the set method as setName("tom"); This process is called setter injection.

To set properties that reference other beans , subelement of is used as shown below,
< bean id="bean1" class="bean1impl" >
< property name="game" >
< ref bean="bean2" / >
< / property >
< / bean >
< bean id="bean2" class="bean2impl" / >

Constructor injection: For constructor injection, we use constructor with parameters as shown below,

public class namebean {
String name;
public namebean(String a) {
name = a;
}
}

We will set the property 'name' while creating an instance of the bean 'namebean' as namebean bean1 = new namebean("tom");

Here we use the < constructor-arg > element to set the property by constructor injection as
< bean id="bean1" class="namebean" >
< constructor-arg >
< value > My Bean Value < / value >
< / constructor-arg >
< / bean >


4. What is spring? What are the various parts of spring framework? What are the different persistence frameworks which could be used with 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. The Spring modules are built on top of the core container, which defines how beans are created, configured, and managed. Each of the modules (or components) that comprise the Spring framework can stand on its own or be implemented jointly with one or more of the others. The functionality of each component is as follows:

The core container: 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.

Spring context: 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.

Spring AOP: 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.

Spring DAO: 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.

Spring ORM: 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.

Spring Web module: 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.

Spring MVC framework: 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.

5. What is AOP? How does it relate with IOC? What are different tools to utilize AOP?


Aspect-oriented programming, or AOP, is a programming technique that allows programmers to modularize crosscutting concerns, or behaviour that cuts across the typical divisions of responsibility, such as logging and transaction management. The core construct of AOP is the aspect, which encapsulates behaviours affecting multiple classes into reusable modules. AOP and IOC are complementary technologies in that both apply a modular approach to complex problems in enterprise application development. In a typical object-oriented development approach you might implement logging functionality by putting logger statements in all your methods and Java classes. In an AOP approach you would instead modularize the logging services and apply them declaratively to the components that required logging. The advantage, of course, is that the Java class doesn't need to know about the existence of the logging service or concern itself with any related code. As a result, application code written using Spring AOP is loosely coupled. The best tool to utilize AOP to its capability is AspectJ. However AspectJ works at the byte code level and you need to use AspectJ compiler to get the aop features built into your compiled code. Nevertheless AOP functionality is fully integrated into the Spring context for transaction management, logging, and various other features. In general any AOP framework control aspects in three possible ways:

Joinpoints: Points in a program's execution. For example, joinpoints could define calls to specific methods in a class
Pointcuts: Program constructs to designate joinpoints and collect specific context at those points
Advices: Code that runs upon meeting certain conditions. For example, an advice could log a message before executing a joinpoint

6. What are the advantages of spring framework?

Spring has layered architecture. Use what you need and leave you don't need.
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.
7. Can you name a tool which could provide the initial ant files and directory structure for a new spring project?


Appfuse or equinox.

8. Explain BeanFactory in spring.

Bean factory is an implementation of the factory design pattern and its function is to create and dispense beans. As the bean factory knows about many objects within an application, it is able to create association between collaborating objects as they are instantiated. This removes the burden of configuration from the bean and the client. There are several implementation of BeanFactory. The most useful one is "org.springframework.beans.factory.xml.XmlBeanFactory" It loads its beans based on the definition contained in an XML file. To create an XmlBeanFactory, pass a InputStream to the constructor. The resource will provide the XML to the factory.
BeanFactory factory = new XmlBeanFactory(new FileInputStream("myBean.xml"));

This line tells the bean factory to read the bean definition from the XML file. The bean definition includes the description of beans and their properties. But the bean factory doesn't instantiate the bean yet. To retrieve a bean from a 'BeanFactory', the getBean() method is called. When getBean() method is called, factory will instantiate the bean and begin setting the bean's properties using dependency injection.

myBean bean1 = (myBean)factory.getBean("myBean");

9. Explain the role of ApplicationContext in spring.


While Bean Factory is used for simple applications; the Application Context is spring's more advanced container. Like 'BeanFactory' it can be used to load bean definitions, wire beans together and dispense beans upon request. It also provide

1) A means for resolving text messages, including support for internationalization.
2) A generic way to load file resources.
3) Events to beans that are registered as listeners.

Because of additional functionality, 'Application Context' is preferred over a BeanFactory. Only when the resource is scarce like mobile devices, 'BeanFactory' is used. The three commonly used implementation of 'Application Context' are

1. ClassPathXmlApplicationContext : It Loads context definition from an XML file located in the classpath, treating context definitions as classpath resources. The application context is loaded from the application's classpath by using the code

ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");

2. FileSystemXmlApplicationContext : It loads context definition from an XML file in the filesystem. The application context is loaded from the file system by using the code

ApplicationContext context = new FileSystemXmlApplicationContext("bean.xml");

3. XmlWebApplicationContext : It loads context definition from an XML file contained within a web application.

10. How does Spring supports DAO in hibernate?

Spring’s HibernateDaoSupport class is a convenient super class for Hibernate DAOs. It has handy methods you can call to get a Hibernate Session, or a SessionFactory. The most convenient method is getHibernateTemplate(), which returns a HibernateTemplate. This template wraps Hibernate checked exceptions with runtime exceptions, allowing your DAO interfaces to be Hibernate exception-free.
Example:

public class UserDAOHibernate extends HibernateDaoSupport {

public User getUser(Long id) {
return (User) getHibernateTemplate().get(User.class, id);
}
public void saveUser(User user) {
getHibernateTemplate().saveOrUpdate(user);
if (log.isDebugEnabled()) {
log.debug(“userId set to: “ + user.getID());
}
}
public void removeUser(Long id) {
Object user = getHibernateTemplate().load(User.class, id);
getHibernateTemplate().delete(user);
}

}


11. What are the id generator classes in hibernate?

increment: It generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. It should not the used in the clustered environment.
identity: It supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int.
sequence: The sequence generator uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int
hilo: The hilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database. Do not use this generator with connections enlisted with JTA or with a user-supplied connection.
seqhilo: The seqhilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a named database sequence.
uuid: The uuid generator uses a 128-bit UUID algorithm to generate identifiers of type string, unique within a network (the IP address is used). The UUID is encoded as a string of hexadecimal digits of length 32.
guid: It uses a database-generated GUID string on MS SQL Server and MySQL.
native: It picks identity, sequence or hilo depending upon the capabilities of the underlying database.
assigned: lets the application to assign an identifier to the object before save() is called. This is the default strategy if no element is specified.
select: retrieves a primary key assigned by a database trigger by selecting the row by some unique key and retrieving the primary key value.
foreign: uses the identifier of another associated object. Usually used in conjunction with a primary key association.

12. How is a typical spring implementation look like?

For a typical Spring Application we need the following files

1. An interface that defines the functions.
2. An Implementation that contains properties, its setter and getter methods, functions etc.,
3. A XML file called Spring configuration file.
4. Client program that uses the function.


13. How do you define hibernate mapping file in spring?

Add the hibernate mapping file entry in mapping resource inside Spring’s applicationContext.xml file in the web/WEB-INF directory.

< property name="mappingResources" >
< list >
< value > org/appfuse/model/User.hbm.xml < / value >
< / list >
< / property >


14. How do you configure spring in a web application?

It is very easy to configure any J2EE-based web application to use Spring. At the very least, you can simply add Spring’s ContextLoaderListener to your web.xml file:

< listener >
< listener-class > org.springframework.web.context.ContextLoaderListener < / listener-class >
< / listener >


15. Can you have xyz.xml file instead of applicationcontext.xml?

ContextLoaderListener is a ServletContextListener that initializes when your webapp starts up. By default, it looks for Spring’s configuration file at WEB-INF/applicationContext.xml. You can change this default value by specifying a element named “contextConfigLocation.” Example:

< listener >
< listener-class > org.springframework.web.context.ContextLoaderListener

< context-param >
< param-name > contextConfigLocation < / param-name >
< param-value > /WEB-INF/xyz.xml< / param-value >
< / context-param >

< / listener-class >
< / listener >



16. How do you configure your database driver in spring?

Using datasource "org.springframework.jdbc.datasource.DriverManagerDataSource". Example:

< bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
< property name="driverClassName" >
< value > org.hsqldb.jdbcDriver < / value >
< / property >
< property name="url" >
< value > jdbc:hsqldb:db/appfuse < / value >
< / property >
< property name="username" > < value > sa < / value > < / property >
< property name="password" > < value > < / value > < / property >
< / bean >


17. How can you configure JNDI instead of datasource in spring applicationcontext.xml?

Using "org.springframework.jndi.JndiObjectFactoryBean". Example:

< bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean" >
< property name="jndiName" >
< value > java:comp/env/jdbc/appfuse < / value >
< / property >
< / bean >

18. What are the key benefits of Hibernate?

These are the key benifits of Hibernate:
Transparent persistence based on POJOs without byte code processing
Powerful object-oriented hibernate query language
Descriptive O/R Mapping through mapping file.
Automatic primary key generation
Hibernate cache: Session Level, Query and Second level cache.
Performance: Lazy initialization, Outer join fetching, Batch fetching

19. What is hibernate session and session factory? How do you configure sessionfactory in spring configuration file?

Hibernate Session is the main runtime interface between a Java application and Hibernate. SessionFactory allows applications to create hibernate session by reading hibernate configurations file hibernate.cfg.xml.

// Initialize the Hibernate environment
Configuration cfg = new Configuration().configure();
// Create the session factory
SessionFactory factory = cfg.buildSessionFactory();
// Obtain the new session object
Session session = factory.openSession();

The call to Configuration().configure() loads the hibernate.cfg.xml configuration file and initializes the Hibernate environment. Once the configuration is initialized, you can make any additional modifications you desire programmatically. However, you must make these modifications prior to creating the SessionFactory instance. An instance of SessionFactory is typically created once and used to create all sessions related to a given context.
The main function of the Session is to offer create, read and delete operations for instances of mapped entity classes. Instances may exist in one of three states:

transient: never persistent, not associated with any Session
persistent: associated with a unique Session
detached: previously persistent, not associated with any Session

A Hibernate Session object represents a single unit-of-work for a given data store and is opened by a SessionFactory instance. You must close Sessions when all work for a transaction is completed. The following illustrates a typical Hibernate session:
Session session = null;
UserInfo user = null;
Transaction tx = null;
try {
session = factory.openSession();
tx = session.beginTransaction();
user = (UserInfo)session.load(UserInfo.class, id);
tx.commit();
} catch(Exception e) {
if (tx != null) {
try {
tx.rollback();
} catch (HibernateException e1) {
throw new DAOException(e1.toString()); }
} throw new DAOException(e.toString());
} finally {
if (session != null) {
try {
session.close();
} catch (HibernateException e) { }
}
}

20. What is the difference between hibernate get and load methods?

The load() method is older; get() was added to Hibernate’s API due to user request. The difference is trivial:
The following Hibernate code snippet retrieves a User object from the database:
User user = (User) session.get(User.class, userID);

The get() method is special because the identifier uniquely identifies a single instance of a class. Hence it’s common for applications to use the identifier as a convenient handle to a persistent object. Retrieval by identifier can use the cache when retrieving an object, avoiding a database hit if the object is already cached.
Hibernate also provides a load() method:
User user = (User) session.load(User.class, userID);

If load() can’t find the object in the cache or database, an exception is thrown. The load() method never returns null. The get() method returns
null if the object can’t be found. The load() method may return a proxy instead of a real persistent instance. A proxy is a placeholder instance of a runtime-generated subclass (through cglib or Javassist) of a mapped persistent class, it can initialize itself if any method is called that is not the mapped database identifier getter-method. On the other hand, get() never returns a proxy. Choosing between get() and load() is easy: If you’re certain the persistent object exists, and nonexistence would be considered exceptional, load() is a good option. If you aren’t certain there is a persistent instance with the given identifier, use get() and test the return value to see if it’s null. Using load() has a further implication: The application may retrieve a valid reference (a proxy) to a persistent instance without hitting the database to retrieve its persistent state. So load() might not throw an exception when it doesn’t find the persistent object in the cache or database; the exception would be thrown later, when the proxy is accessed.

21. What type of transaction management is supported in hibernate?

Hibernate communicates with the database via a JDBC Connection; hence it must support both managed and non-managed transactions.

Non-managed in web containers:

< bean id="transactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager" >
< property name="sessionFactory" >
< ref local="sessionFactory" / >
< / property >
< / bean >

Managed in application server using JTA:

< bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager." >
< property name="sessionFactory" >
< ref local="sessionFactory" / >
< / property >
< / bean >


22. What is lazy loading and how do you achieve that in hibernate?


Lazy setting decides whether to load child objects while loading the Parent Object. You need to specify parent class.Lazy = true in hibernate mapping file. By default the lazy loading of the child objects is true. This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent. In this case hibernate issues a fresh database call to load the child when getChild() is actually called on the Parent object. But in some cases you do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database. Examples: Address child of User class can be made lazy if it is not required frequently. But you may need to load the Author object for Book parent whenever you deal with the book for online bookshop.

Hibernate does not support lazy initialization for detached objects. Access to a lazy association outside of the context of an open Hibernate session will result in an exception.

23. What are the different fetching strategies in Hibernate?

Hibernate3 defines the following fetching strategies:

Join fetching - Hibernate retrieves the associated instance or collection in the same SELECT, using an OUTER JOIN.

Select fetching - a second SELECT is used to retrieve the associated entity or collection. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.

Subselect fetching - a second SELECT is used to retrieve the associated collections for all entities retrieved in a previous query or fetch. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.

Batch fetching - an optimization strategy for select fetching - Hibernate retrieves a batch of entity instances or collections in a single SELECT, by specifying a list of primary keys or foreign keys.

24. What are different types of cache hibernate supports?

Caching is widely used for optimizing database applications. Hibernate uses two different caches for objects: first-level cache and second-level cache. First-level cache is associated with the Session object, while second-level cache is associated with the Session Factory object. By default, Hibernate uses first-level cache on a per-transaction basis. Hibernate uses this cache mainly to reduce the number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction, containing all the modifications. To reduce database traffic, second-level cache keeps loaded objects at the Session Factory level between transactions. These objects are available to the whole application, not just to the user running the query. This way, each time a query returns an object that is already loaded in the cache, one or more database transactions potentially are avoided. In addition, you can use a query-level cache if you need to cache actual query results, rather than just persistent objects. The query cache should always be used in conjunction with the second-level cache. Hibernate supports the following open-source cache implementations out-of-the-box:

EHCache is a fast, lightweight, and easy-to-use in-process cache. It supports read-only and read/write caching, and memory and disk-based caching. However, it does not support clustering.
OSCache is another open-source caching solution. It is part of a larger package, which also provides caching functionalities for JSP pages or arbitrary objects. It is a powerful and flexible package, which, like EHCache, supports read-only and read/write caching, and memory- and disk-based caching. It also provides basic support for clustering via either JavaGroups or JMS.
SwarmCache is a simple cluster-based caching solution based on JavaGroups. It supports read-only or nonstrict read/write caching (the next section explains this term). This type of cache is appropriate for applications that typically have many more read operations than write operations.
JBoss TreeCache is a powerful replicated (synchronous or asynchronous) and transactional cache. Use this solution if you really need a true transaction-capable caching architecture.
Commercial Tangosol Coherence cache.
25. What are the different caching strategies?

The following four caching strategies are available:
Read-only: This strategy is useful for data that is read frequently but never updated. This is by far the simplest and best-performing cache strategy.
Read/write: Read/write caches may be appropriate if your data needs to be updated. They carry more overhead than read-only caches. In non-JTA environments, each transaction should be completed when Session.close() or Session.disconnect() is called.
Nonstrict read/write: This strategy does not guarantee that two transactions won't simultaneously modify the same data. Therefore, it may be most appropriate for data that is read often but only occasionally modified.
Transactional: This is a fully transactional cache that may be used only in a JTA environment.
26. How do you configure 2nd level cache in hibernate?

To activate second-level caching, you need to define the hibernate.cache.provider_class property in the hibernate.cfg.xml file as follows:
< hibernate-configuration >
< session-factory >
< property name="hibernate.cache.provider_class" >org.hibernate.cache.EHCacheProvider< / property >
< / session-factory >
< / hibernate-configuration >

By default, the second-level cache is activated and uses the EHCache provider.
To use the query cache you must first enable it by setting the property hibernate.cache.use_query_cache to true in hibernate.properties.

27. What is the difference between sorted and ordered collection in hibernate?

A sorted collection is sorted in-memory using java comparator, while order collection is ordered at the database level using order by clause.

28. What are the types of inheritance models and describe how they work like vertical inheritance and horizontal?

There are three types of inheritance mapping in hibernate:

Example: Let us take the simple example of 3 java classes. Class Manager and Worker are inherited from Employee Abstract class.
1. Table per concrete class with unions: In this case there will be 2 tables. Tables: Manager, Worker [all common attributes will be duplicated]
2. Table per class hierarchy: Single Table can be mapped to a class hierarchy. There will be only one table in database called 'Employee' that will represent all the attributes required for all 3 classes. But it needs some discriminating column to differentiate between Manager and worker;
3. Table per subclass: In this case there will be 3 tables represent Employee, Manager and Worker


If you have any questions that you want answer for, please leave a comment on this page OR drop a note to Snehal[at]TechProceed[dot]com and I will answer them.

Happy Learning!

Thursday, February 9, 2012

J2EE Design Patterns - Interview Questions

J2EE Design Patterns - Interview Questions The following are some questions that you might encounter when you face an Interview for a position of a Senior Java/J2EE Developer. Design Patterns are very exciting and useful and most managers expect their developers to have a sound understanding of the most important patterns. 

Questions


What are design patterns?

A pattern is a proven (and recurring) solution to a problem in a context. Each pattern describes a problem which occurs time and again in our environment, and describes its solution to this problem in such a way that we can use this solution any number of times. In simple words, there are a lot of common problems which a lot of developers have faced over time. These common problems ideally should have a common solution too. It is this solution when documented and used over and over becomes a design pattern.

Can we always apply the same solution to different problems at hand?

No. Design patterns would study the different problems at hand. To these problems then it would suggest different design patterns to be used. However, the type of code to be written in that design pattern is solely the discretion of the Project Manager who is handling that project.

What should be the level of detail/abstraction which should be provided by a design pattern?

Design patterns should present a higher abstraction level though it might include details of the solution. However, these details are lower abstractions and are called strategies. There may be more than one way to apply these strategies in implementing the patterns. The details of implementation are usually upto the developer who is coding at the ground level. 

What are the most common problems which one faces during the application design phase that are solved by design patterns?

Some are:

1. Identifying components, internal structures of the components, and relationships between components. 
2. Determining component granularity and appropriate interactions 
3. Defining component interfaces. 

How does one decide which Design pattern to use in our application?

We need to follow these steps:

1. We need to understand the problem at hand. Break it down to finer grained problems. Each design pattern is meant to solve certain kinds of problems. This would narrow down our search for design patterns. 
2. Read the problem statement again along with the solution which the design pattern will provide. This may instigate to change a few patterns that we are to use. 
3. Now figure out the interrelations between different patterns. Also decide what all patterns will remain stable in the application and what all need to change (with respect to Change Requests received from the clients). 


What is Refactoring?

Learning different design patterns is not sufficient to becoming a good designer.We have to understand these patterns and use them where they have more benefits. Using too many patterns (more than required) would be over-engineering and using less design patterns than required would be under-engineering. In both these scenarios we use refactoring. Refactoring is a change made to the internal structure of the software to make it easier to understand and cheaper to modify, without changing its observable behaviour.

What are Antipatterns?

Though the use of patterns fulfils our objectives in the applications; there are also several instances where several applications did not fulfill their goals. The architects of these applications too need to document these wrong decisions.This helps others by preventing them from repeating these mistakes in their applications. Such documented mistakes are called antipatterns. 

As we do development in tiers, how do we divide patterns in tiers?

The Sun Java Center has classified the patterns in three tiers. These are:

Presentation tier patterns for web-component tier, 
Business tier patterns for business logic (EJB) tier, and 
Integration tier patterns for connection to the databases. 

What are the Presentation Tier Patterns? 

The presentation tier patterns are: 

Intercepting filter, Front Controller, View Helper, Composite View, Service-to-Worker, and Dispatcher View.

What are the Business Tier Patterns? 

The business tier patterns are:

Business delegate, Value Object, Session Façade, Composite Entity, Value Object Assembler, Value List Handler, and Service Locator.

What are the Integration Tier Patterns? 

Integration tier patterns are:

Data Access Object (DAO) and Service Activator

What is Intercepting Filter pattern?

Provides a solution for pre-processing and post-processing a request. It allows us to declaratively apply filters for intercepting requests and responses. For ex. Servlet filters.

What is Front Controller pattern?

It manages and handles requests through a centralized code. This could either be through a servlet or a JSP (through a Java Bean). This Controller takes over the common processing which happens on the presentation tier. The front controller manages content retrieval, security, view management and retrieval.

What is View Helper pattern?

There generally are two parts to any application – the presentation and the business logics. The “View” is responsible for the output-view formatting whereas “Helper” component is responsible for the business logic. Helper components do content retrieval, validation and adaptation. Helper components generally use Business delegate pattern to access business classes.

What is Composite View pattern?

This pattern is used for creating aggregate presentations (views) from atomic sub-components. This architecture enables says piecing together of elementary view components which makes the presentation flexible by allowing personalization and customization.

What is Service to Worker pattern?

This is used in larger applications wherein one class is used to process the requests while the other is used to process the view part. This differentiation is done for maintainability.

What is Dispatcher View pattern?

This is similar to Service to Worker pattern except that it is used for smaller applications. In this one class is used for both request and view processing.

What is Business Delegate pattern?

This pattern is used to reduce the coupling between the presentation and business-logic tier. It provides a proxy to the façade from where one could call the business classes or DAO class. This pattern can be used with Service Locator pattern for improving performance.

What is Value Object pattern?

Value Object is a serializable object which would contain lot of atomic values.These are normal java classes which may have different constructors (to fill in the value of different data) and getter methods to get access to these data. VOs are used as a course grained call which gets lots of data in one go (this reduces remote overhead). The VO is made serializable for it to be transferred between different tiers within a single remote method invocation

What is Session Façade pattern?

This pattern hides the complexity of business components and centralizes the workflow. It provides course-grained interfaces to the clients which reduces the remote method overhead. This pattern fits well with declarative transactions and security management. 

What is Value Object Assembler pattern?

This pattern allows for composing a Value Object from different sources which could be EJBs, DAOs or Java objects. 

What is Value List Handler pattern?

This pattern provides a sound solution for query execution and results processing. 

What is Service Locator pattern?

It provides a solution for looking-up, creating and locating services and encapsulating their complexity. It provides a single point of control and it also improves performance. 

What is Data Access Object pattern?

It provides a flexible and transparent access to the data, abstracts the data sources and hides the complexity of Data persistence layer. This pattern provides for loose coupling between business and data persistence layer. 

What is EJB Command pattern?

Session Façade and EJB Command patterns are competitor patterns. It wraps business logic in command beans, decouples the client and business logic tier, and reduces the number of remote method invocations. 

What is Version Number pattern?

This pattern is used for transaction and persistence and provides a solution for maintaining consistency and protects against concurrency. Every time a data is fetched from the database, it comes out with a version number which is saved in the database. Once any update is requested on the same row of the database, this version is checked. If the version is same, the update is allowed else not.

What all patterns are used to improve performance and scalability of the application?

Value Object, Session Façade, Business Delegate and Service Locator.

What design patterns could be used to manage security?

Single Access Point, Check point and Role patterns


* * *

If you have any more questions on J2EE concepts that you have faced during your interviews and wish to add them to this collection - Please drop a note to me and I shall be glad to add them to this list.



J2EE Interview Questions

The following are some questions you might encounter with respect to the J2EE Technology in any Interview for a Java J2EE Developer. The questions below are pretty exhaustive and practically speaking, you might not be asked most of the questions because - interviewers might prefer to test out your knowledge of core J2EE technologies like Servlets, JSPs, Struts, Hibernate etc. Nonetheless, there is nothing wrong in being prepared and the questions below would help you prepare for your J2EE Interview.

Questions:

1. What is J2EE?

J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multitier, web-based applications.

2. What is the J2EE module?

A J2EE module consists of one or more J2EE components for the same container type and one component deployment descriptor of that type.

3. What are the components of J2EE application?

A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components:
* Application clients and applets are client components.
* Java Servlet and JavaServer Pages (JSP) technology components are web components.
* Enterprise JavaBeans (EJB) components are business components.
* Resource adapter components provided by EIS and tool vendors.

4. What does application client module contain?

The application client module contains:
*class files
*an application client deployment descriptor.

Application client modules are packaged as JAR files with a .jar extension.

5. What does web module contain?

The web module contains:
*JSP files,
*class files for servlets,
*GIF and HTML files, and
*a Web deployment descriptor.

Web modules are packaged as JAR files with a .war (Web ARchive) extension.

6. What are the differences between Ear, Jar and War files? Under what circumstances should we use each one?

There are no structural differences between the files; they are all archived using zip-jar compression. However, they are intended for different purposes.

*Jar files are intended to hold generic libraries of Java classes, resources, auxiliary files, etc.
*War files are intended to contain complete Web applications.
*Ear files are intended to contain complete enterprise applications.

Each type of file (.jar, .war, .ear) is processed uniquely by application servers, servlet containers, EJB containers, etc.

7. What is an applet?

A J2EE component that typically executes in a Web browser but can execute in a variety of other applications or devices that support the applet programming model.

8. What is applet container?

A container that includes support for the applet programming model.

9. What is application assembler?

A person who combines J2EE components and modules into deployable application units

10. What is application client?

A first-tier J2EE client component that executes in its own Java virtual machine. Application clients have access to some J2EE platform APIs.

11. What is application client container?

A container that supports application client components.

12. What is application client module?

A software unit that consists of one or more classes and an application client deployment descriptor.

13. What is application component provider?

A vendor that provides the Java classes that implement components' methods, JSP page definitions, and any required deployment descriptors.

14. What is application configuration resource file?

An XML file used to configure resources for a Java Server Faces application, to define navigation rules for the application, and to register converters, Validator, listeners, renders, and components with the application.

15. What is build file?

The XML file that contains one or more ant targets. A target is a set of tasks you want to be executed. When starting asant, you can select which targets you want to have executed. When no target is given, the project's default target is executed.

ant - is a tool that is used to build web applications

16. What is deployment?

The process whereby software is installed into an operational environment. For ex: deploying an EAR file into a Weblogic Server.

17. What is deployment descriptor?

An XML file provided with each module and J2EE application that describes how they should be deployed. The deployment descriptor directs a deployment tool to deploy a module or application with specific container options and describes specific configuration requirements that a deployer must resolve.

18. What is HTML?

Hypertext Markup Language. A markup language for hypertext documents on the Internet. HTML enables the embedding of images, sounds, video streams, form fields, references to other objects with URLs, and basic text formatting.

19. What is HTTP?

Hypertext Transfer Protocol. The Internet protocol used to retrieve hypertext objects from remote hosts. HTTP messages consist of requests from client to server and responses from server to client.

20. What is HTTPS?

HTTP layered over the SSL protocol. It is the secure version of the HTTP protocol

21. What is Java 2 Platform, Micro Edition (J2ME)?

A highly optimized Java runtime environment targeting a wide range of consumer products, including pagers, cellular phones, screen phones, digital set-top boxes, and car navigation systems.

22. What is JDBC?

An JDBC for database-independent connectivity between the J2EE platform and a wide range of data sources.

23. What is JNDI?

Abbreviate of Java Naming and Directory Interface. It is used as part of JDBC

24. What is query string?

A component of an HTTP request URL that contains a set of parameters and values that affect the handling of the request

25. What is resource adapter?

A system-level software driver that is used by an EJB container or an application client to connect to an enterprise information system. A resource adapter typically is specific to an enterprise information system. It is available as a library and is used within the address space of the server or client using it. A resource adapter plugs in to a container. The application components deployed on the container then use the client API (exposed by the adapter) or tool-generated high-level abstractions to access the underlying enterprise information system. The resource adapter and EJB container collaborate to provide the underlying mechanisms-transactions, security, and connection pooling-for connectivity to the enterprise information system.

26. What is Secure Socket Layer (SSL)?

A technology that allows Web browsers and Web servers to communicate over a secured connection.

27. What is URI?

Uniform resource identifier. A globally unique identifier for an abstract or physical resource. A URL is a kind of URI that specifies the retrieval protocol (http or https for Web applications) and physical location of a resource (host name and host-relative path). A URN is another type of URI.

28. What is URL?

Uniform resource locator. A standard for writing a textual reference to an arbitrary piece of data in the World Wide Web. A URL looks like this:
protocol://host/local info

where protocol specifies a protocol for fetching the object (such as http or ftp), host specifies the Internet name of the targeted host, and local info is a string (often a file name) passed to the protocol handler on the remote host.

29. What is URL path?

The part of a URL passed by an HTTP request to invoke a servlet. A URL path consists of the context path + servlet path + path info, where Context path is the path prefix associated with a servlet context of which the servlet is a part. If this context is the default context rooted at the base of the Web server's URL namespace, the path prefix will be an empty string. Otherwise, the path prefix starts with a / character but does not end with a / character. Servlet path is the path section that directly corresponds to the mapping that activated this request. This path starts with a / character. Path info is the part of the request path that is not part of the context path or the servlet path

30. What is URN?

Uniform resource name. A unique identifier that identifies an entity but doesn't tell where it is located. A system can use a URN to look up an entity locally before trying to find it on the Web. It also allows the Web location to change, while still allowing the entity to be found.

* * *


If you have any more questions on J2EE concepts that you have faced during your interviews and wish to add them to this collection - Please drop a note to me and I shall be glad to add them to this list.