Miscellan – Web Technologies

Q# How do you configure maven? What are the advantages of maven over ant build?

Maven is just a framework of plugins that uses Ant underneath. It stores jar files in a remote repository for easy sharing. Maven is easier to use; there is no need to write large build.xml files since most common tasks are available as plugins.
You have a settings.xml and one or several pom.xml.
The settings.xml is optional and is used to specify the repository location, security and deployment settings. If it is absent default values are used. It may also contain repository authentication informatio and username and passoword for the server on which the generated package is deployed.
Maven Repository
Maven will automatically download artifacts from the online maven repository if the dependencies are not locally available in the repository. The jars are placed in a local maven repository(relative path=.m2/repo).
It contains the following information:

  • the type of packaging,
  • information about the project dependencies(artifacts or dependencies of those artifacts),
  • artifact name
  • artifact version,
  • artifact scope(default scope means the generated package will include this artifact while “provided” means they will be provided by the deployment container),
  • maven plugins that are to be used during the build process(certain plugins such as mvn:clean, mvn:compile, mvn:package are included by default within the maven distribution),
  • dependencies on third party maven repositories

When executing a task or goal, Maven looks for the POM in the current directory. It reads the POM, gets the needed configuration information such as project dependencies, then executes the goal. The goal may be a custom goal or one that is available in a maven plugin or inbuilt into maven.
Maven commands
mvn compile
mvn package
mvn install
are common maven commands.
Maven has plugins for all “common” tasks so that all you have to do is add some information to configuration files. These are built over Ant tasks.

Q# Java Messaging Service – here we go again

Two useful links from cuppajava site that proves handy:

Q# For what functionality did you use JMX in any of your applications?

customizing JBoss JMX console to change the state of custom beans at runtime

Q# Have you performed any tomcat or jboss administration?

For the most part developers do very little with jboss and tomcat administration – mainly deployment, datasource configuration. I’m sure jboss and tomcat have a lot of proprietary features that are powerful but normally we don’t use them and instead we stick to standard J2EE techniques and third party frameworks etc. In a production environment the jboss/tomcat administrator may do some tuning like change the # of connections in jdbc pool, JVM args, etc. but normally a developer doesn’t care about this stuff. jboss has a UI for configuration:
see http://docs.jboss.org/jbossas/6/Admin_Console_Guide/en-US/pdf/Admin_Console_Guide.pdf
For tomcat

Q# How does inter-portlet communication take place in liferay?

Q# Describe the JSF life cycle
Request Processing Scenarios:
1. Faces request: A servlet request that was sent from a previously generated Faces response. i.e. from a jsf page. eg a JSF form submission
2. Non Faces request: A servlet request that was sent from a non JSF page such as a JSP page without JSF tags.
3. Faces response: A servlet response rendered by the RENDER RESPONSE PHASE
4. Non Faces response: A servlet response not rendered by the RENDER RESPONSE PHASE
eg. a jsp page which does not incorporate JSF tags is rendered.

Scenario 1: Non Faces Request generates Faces Response
eg. When a hyperlink is clicked which invokes a JSF page. The non Faces request is mapped to the FacesServlet which generates a Faces response by generating a view which is basically a tree of UI componenents. It then goes to the RENDER RESPONSE PHASE.
Scenario 2: Faces Request generates Non Faces Response
A JSF page rendered through the RENDER RESPONSE PHASE when submitted may render a non JSF page without JSF tags. The RENDER RESPONSE PHASE is skipped and so are all the intermediate steps in the life cycle.
Scenario 3: Faces Request generates Faces Response
This is the most common scenario in a JSF life cycle. A JSF page rendered by a RENDER RESPONSE PHASE generates a Faces request mapped ot the Faces Servlet. All convertors, validators and listeners are invoked as part of the JSF life cycle and a Faces Response is rendered. This process is described below:
The following shows the complete steps from Faces Request to Faces Response.
When a request is made from a JSF page i.e. Faces Request postback- such as submission of a JSF page, the JSF implementation restores the view(tree of JSF UI components) by using state information saved on the server or client.
If this is a fresh request for a JSF page, an empty view comprising of JSF UI components is created and moves to the RENDER RESPONSE PHASE bypassing intermediate steps.
After the view is restored, the component tree extracts the request values and stores it, after conversion. If the conversion fails, validation errors are generated. If any listeners are registered, the JSF implementation broadcasts events to these listeners. In short components are set new values, messages and events are queued.
The JSF implementation processes all validator registred with the UI components and applies these rules to the stored value in the JSF UI componenets. If values are invalid, error messages are generated, and the cycle moves to RENDER RESPONSE PHASE and displays all error message queue up. If events have been queued up at this stage, the JSF implementation broadcasts tehm tho these liseteners.
The JSF implementation updates the model (JSF backing beans) with values from the UI componenets. If the conversion from UI component data types to model data types fails, errors are generated and queued up and the cycle moves to the RENDER RESPONSE PHASE Where these error messages are displayed. If events are queued up at this stage the JSF implementation broadcasts them to interested listeners.
The JSF implementation consults the application configuration and processes the request by handlers after which the navigation rules are looked up to find which view is to be shown. The cycle then moves to the RENDER RESPONSE PHASE. If events are fired these broadcast to interested listeners.
The JSF implementation hands delegates the remaining steps to the JSP container to render the Faces view.
If the request is postback the errors that were encountered in the above steps will be displayed on the original page.
The state of the response is saved to make it available to the next RESTORE VIEW PHASE.
If this is a fresh request the components are already added to the tree creating an empty view, and this will be rendered by the JSP container.

Notes on Spring and Hibernate

Q# How do you implement transaction handling in spring and hibernate?

This looks like a very good explanation of spring and hibernate transaction handling:
It first discusses hibernate the traditional way, using session etc.then describes hibernate using spring templates.
With Spring, you do not need to implement code for obtaining Session objects, starting and committing transactions, and handling Hibernate exceptions. Instead, you use a HibernateTemplate instance to delegate persistence calls to Hibernate, without direct interaction with Hibernate.
This page would clear any questions about spring/hibernate including transaction handling, etc.
Spring declarative transaction types
Enum Constants
Enum Constant and Description
Support a current transaction, throw an exception if none exists.
Execute within a nested transaction if a current transaction exists, behave like PROPAGATION_REQUIRED else.
Execute non-transactionally, throw an exception if a transaction exists.
Execute non-transactionally, suspend the current transaction if one exists.
Support a current transaction, create a new one if none exists.
Create a new transaction, and suspend the current transaction if one exists.
Support a current transaction, execute non-transactionally if none exists.

JDBC is a Java standard for database connection. JPA isolates the Java developer from the inner workings of JDBC and database operations. Hibernate, EclipseLink, OpenJPA and Data Nucleus are famous JPA implementations. JTA is a standard for transactions, allowing for management of multiple transactions among multiple databases. JPA utilizes JDBC for database connections and SQL-related operations, and -optionally- utilizes JTA for delegating distributed transaction management details to it.

Q# How does hibernate implement caching programatically?

There are two types of caching – first-level and second-level. First-level cache is hibernate’s internal cache that it uses for optimizing. Second-level caching, is what we normally refer to as caching generally. Secondary level caching is usually implemented using an algorithm like Least Recently Used algorithm.
By storing the data in a cache instead of relying solely on the database, you may be able to significantly reduce the load on the database, and possibly to increase overall performance as well.
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.

Implementing caching programatically
We specify which classes to cache and the caching params but we don’t really write code to invoke the cache.
http://www.informit.com/articles/article.aspx?p=353736&seqNum=5 #Configuring a Cache.
If you feel certain that the problems are due to the amount of traffic between your application and the database. The solution in this case may be a cache. By storing the data in a cache instead of relying solely on the database, you may be able to significantly reduce the load on the database, and possibly to increase overall performance as well.
Regardless of which cache you choose, you will need to tell Hibernate what sort of cache rules should be applied to your data. This is defined using the cache tag. You can place the cache tag in your *.hbm.xml files or in the hibernate.cfg.xml file. Alternatively, you can configure cache settings programmatically using the Configuration object.

Q# How do you configure hibernate using spring?

Hibernate Integration with Spring http://java.dzone.com/articles/spring-hibernate-persistence
When the application uses hibernate using hibernate.cfg.xml, the Session Factory configured through it is available to the DAO class.

SessionFactory sessionFactory =new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession();
Transaction tx = sesssion.beginTransaction();
Object obj = session.get(....);

Spring’s Hibernate Support
The datasource is configured in Spring’s application context xml. The datasource might be configured using a JNDI context as well. Spring provides support for hibernate through the HibernateDaoSupport class. The HibernateDao support wraps the HibernateTemplate which in turn wraps the Hibernate session object which in turn wraps the Hibernate Session Factory. The session factory is passed a reference to the configured datasource in the spring context. The hibernate template is an abstraction around the usual boilerplate code written when only hibernate is used; and takes care of managing transactions, handling exceptions, managing connections and delegating persistence calls to hibernate. save(), load(), get(), which is invoked on the hibernate session, can be invoked on the hibernate template as well, in addition to find() and findByCriteria() not exposed by the hibernate session.
Spring’s IOC layer also allows the DAO class to be loosely coupled from the service layer and be configured through xml files. In a spring application, the dao layer is usually separated from the business layer by a service facade pattern. Transaction management can be done decoratively instead of code.
When you use JPA with Spring the underlying Hibernate or EJB3 implementation of the persistence layer is hidden and JPA act as a wrapper over them.

The DAO class(Spring) is a wrapper over HibernateTemplate(Spring) which in turn wraps the Hibernate session object which in turn wraps the Hibernate Session Factory. Obtain session from sessionfactory, open transaction from session, commit/ rollback the transaction and close the session. Get hibernateTemplate(Spring) from SessionFactory(Hibernate) to perform the perisistence operations. Don’t work directly with session in Spring. Spring obtains instances of Session objects from the SessionFactory instance. Exceptions emerging from Hibernate are handled by the Spring layer and transactions can be managed if required declaratively by the Spring layer.

Q# Explain lazy loading and eager fetch in hibernate.

If object A has relation with object B, if you load object A, object B is not loaded from db automatically; it will be loaded only when you do getB(). Eager fetch is the opposite technique. In eager fetch B is loaded when A is loaded if A contains B. The default mechanism is lazy loading.
When to use lazy loading and when to use eager fetch:
Lazy load will not automatically load child objects. It will load child objects only when getChild() is called. Eager fetch will automatically load child objects when the parent object is loaded.
Whether to use lazy load or eager fetch depends on your performance requirements.
If you use eager fetch children were already loaded and are already in memory so accessing these objects will be faster. Memory consumption will be more because more objects are in memory even if they are not needed.If you use lazy load, child objects are loaded only when required (when getter method is invoked). Hence accessing child objects will be somewhat slower but will use lesser memory since objects are loaded only if they are required.

Q# Give some advantages of JPA over hibernate. When do we use hibernate and when do we use JPA?

JPA is a wrapper around ORM technology such as EJB3 and Hibernate among others.
Hibernate 3.0 as well as EJB3 implement and support JPA. Code written using JPA uses a standard Java API so that it is generic and implementation agnostic. I could switch hibernate to use something else like iBatis etc. Beneath JPA, the underlying persistence mechanism could be hibernate or toplink or jbatis etc. JPA delegates the database transactions to the underlying persistence layer. The underlying persistence mechanism could be changed anytime and the JPA code wouldn’t change.

And hibernate 3.0 implements the JPA specification so TopLink and other O/R mapping framework.So your code depends upon JPA Api and its implementation is supplied by any JPA impl vendor framework. So in effect if you use JPA , you are using a standard Java Api and not some orthogonal Api and hence you have flexibility in your system. Say initially you have used Hibernate but now want to shift to Other framework.That means JPA supports pluggable persistence providers. JPA specification is heavily influenced by current O/R mapping frameworks like Hibernate and Top-Link.

Q# What is cascade-all in Hibernate? What are its advantages?

In a hibernate mapping file, if you specify cascade=”none” means that saving or deleting first hibernate object has no affect on related object. cascade=”save” means if first object is saved it automatically saves the related object. Similarly cascade delete will delete related object. cascade=”all” is everything save, delete etc even if they are related with foreign keys. The FK constraints etc. everything gets deleted and hibernate takes care of that.
The code to add a Child looks like this

Parent p = (Parent) session.load(Parent.class, pid);
Child c = new Child();

You can address the frustrations of the explicit call to save() by using cascades.

Cascade in hibernate (saving child objects as well) and cascade in sql(deleting rows in parent table when fk related child tables rows are deleted)

Q# What is dirty checking in hibernate? What are its advantages?

Dirty checking is hibernate is an internal mechanism that ensures that the value of the hibernate POJO object matches what is in the database(synchronizes). If the value does not match it is said to be “dirty” and hence value is refreshed from the database. Hibernate updates only “dirty” objects – only objects that have changed. Hibernate keeps track of which objects are dirty and occasionally “flushes” to ensure the objects are in sync with the db. The advantages of dirty checking is if hibernate doesn’t keep track of which objects are dirty it would have to update all objects that were loaded even if they didn’t change at the final commit of the transaction.

What are bean scopes in Spring?

1. singleton(default*)
Scopes a single bean definition to a single object instance per Spring IoC container.
2. prototype
Scopes a single bean definition to any number of object instances.
3. request
Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
4. session
Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
5. global session
Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

Difference between a Java singleton and a Spring singleton

The Java singleton is scoped by the Java class loader, the Spring singleton is scoped by the container context.
Which basically means that, in Java, you can be sure a singleton is a truly a singleton only within the context of the class loader which loaded it. Other class loaders should be capable of creating another instance of it (provided the class loaders are not in the same class loader hierarchy), despite of all your efforts in code to try to prevent it.
In Spring, if you could load your singleton class in two different contexts and then again we can break the singleton concept.
In summary, Java considers something a singleton if it cannot create more than one instance of that class within a given class loader, whereas Spring would consider something a singleton if it cannot create more than one instance of a class within a given container/context.

Protected: Software versions I have used

This content is password protected. To view it please enter your password below: