Monthly Archives: July 2013

Spring Book – Chapter 13 – Spring and JSF Integration

JSF being one of the very successful, prominent and well backed up web framework, the importance of integration between Spring and JSF is covered in full detail with meaningful pictures and example code in this chapter for readers who are beginners and experts alike.

JavaServer Faces (JSF) is a server side user interface component framework for developing Java technology-based web applications. Developed through the Java Community Process under JSR – 314, it establishes the standard for building server-side user interfaces and have gained tremendous acceptance over the period of time in the Java world. JavaServer Faces APIs are being designed keeping in mind that they can be leveraged by tools that will make web application development even easier and simpler.

This Chapter provides an introduction on how the in famous Spring Framework can be integrated with in famous web framework, Java Server Faces Technologies. The Chapter covers the necessary details of both the Spring Framework and JSF technology in the initial section in the context of Integration and then later on moves towards the concept of concepts which help in easing the integration between the two technologies.

JSF Overview

Before getting into the details of how Sping and JSF Integration, it is important to know basic details of JSF. The following initial sections of this Chapter will cover JSF in some detail so that initial context is set and we can understand the integration in a clear fashion.

JSF Architecture

JSF is based on Model-View-Controller (MVC) architecture. Since it is based on well know MVC design the applications can be designed in a simpler and easy fashion keeping maintainability factor intact. In earlier Chapters we have covered MVC design patter in detail, so I wouldn’t repeat the same in this Chapter.

MVC model’s main purpose is to separate model and presentation to enable developers to set focus on their core skills and collaborate more clearly. If the application demands creating different pages for presentation, developers can concentrate on the view layer rather than model and controller layer as developers have a provision to reuse code for controller and model already written with ease.

Pictorially JSF architecture keeping the essence of MVC design can be represented as shown in Figure 13-1 below.

fig13-01

Figure 13-1. JSF architecture showing off MVC design

JSF Lifecycle

The processing of a request is called lifecycle in JSF. There are different phases which are executed one after the other following “Chain of responsibilities” design pattern. Figure 13-2 below shows the JSF lifecycle.

fig13-02

Figure 13-2. JSF lifecycle

There are various phases constituting the JSF lifecycle. The various lifecycle phases can be summarized as follows:

  • Restore View
  • Apply Request Values
  • Process Validations
  • Update Model Values
  • Invoke Application
  • Render Response

Pictorially the various phases in the JSF lifecycle can be as shown in Figure 13-3 below.

fig13-03

Figure 13-3. JSf lifecycle phases

JSF application in many ways work very much similar to a typical desktop application comprising of components and events. In line with client application, components can create events and can react or listen to events. There are different types of events and there are various places where these events are created and invoked. The events can be classified into three different types as shown below:

  • System events – These events are created at various stages in an application or request lifetime. These events can be configured to evoke globally to all components and others which are related to a component.
  • Phase events – Phase events are coarse grained in nature and are broadcasted before and after every phase. You can use phase listener to check access before a phase is entered. You also have a provision of registering global phase event listener and per view phase event listener. Global phase listener are executed for all requests whereas per view listener only for a request of the specific view.
  • Application events – Application events are created by the application components. JSF has two types of events namely:
    • ValueChangeEvent
    • ActionEvent

Figure 13-4 below pictorially shows the events which are invoked at the various phases in the JSF lifecycle.

fig13-04

Figure 13-4. JSF lifecycle phases along with event invocation points

Page Visitors: 2785

Model View Controller 2 architecture

Spring Book – Chapter 12 – Spring and Struts Integration

My humble effort to explain Spring and Struts integration in detail using code samples for easy understanding for my fellow developers and readers.

Apache Struts is more established, more used and well known MVC2 web framework in the Java world. I am sure anyone experienced with web application will surely have had a chance to work with this one of the pioneers in web framework.

Over the past few years there have been so many buzz words in the world of software development like Inversion of Control (IoC), AOP etc. These paradigms has revolutionized the software development and Spring being one of the frameworks adopting these new technologies into it and have become really good at it.

This Chapter makes a big assumption that the reader is conversant with the Struts Framework and that the reader would like to integrate the Spring Framework into the struts application so as to use the capabilities and out-of-box features provided by the Spring Framework.

If you like to take advantage of these features of Spring you do not have to rebuild the application, but you can integrate your existing Struts application with Spring without much hassle. This Chapter will let you do exactly this so that you can take the advantages of both worlds with good level of confidence and comfort. This Chapter is a very simple one and I am sure you will be able to complete it at one go without trouble whatsoever.

Apache Struts

Apache Struts 2 is an elegant, extensible framework for creating enterprise-ready Java web applications. The framework is designed to streamline the full development cycle, from building, to deploying, to maintaining applications over time.

Apache Struts 2 was originally known as WebWork 2. After working independently for several years, the WebWork and Struts communities joined forces to create Struts2. This new version of Struts is simpler to use and closer to how Struts was always meant to be.

Apache Struts in an MVC2 Java web framework. MVC2 is a servlet-centric architecture.  MVC2 incorporates a clear separation of view and controller. A controller receives all the requests, retrieves data from a Model and forwards it to next view for presentation.

In MVC2, there is a central Servlet (Controller) which calls business logic (Model) and the forwards it particular JSP page (View) that is why it is also called servlet-centric architecture. Pictorially MVC2 implementation is as shown in Figure 12-1 below.

 Model View Controller 2 architecture

Figure 12-1. MVC2 (Servlet-centric architecture)

WebWork was a Java-based web application framework developed by OpenSymphony which got merged into the current Struts2 web application framework. WebWork is built on top of XWork, which provides a generic command pattern framework as well as an Inversion of Control container.

Advantages of integrating Struts with Spring

The advantages of integrating a Struts application into the Spring Framework are:

  • Spring framework is based on new design approach and was designed to resolve the existing problems of existing Java applications. To a larger extent Spring has been successful in living to the expectations. Integrating Struts application with Spring buys in all the advantages provided out-of-box by Spring.
  • Spring framework lets you apply AOP (aspect-oriented programming technique) rather than object-oriented code. This is quite useful in addressing some very core concerns in any modern day enterprise application.
  • Spring provides more control on struts actions. That may depend on the method of integration you choose which we will cover in detail in the following sections of this Chapter.

Struts History

Before going through Spring and Struts integration in detail, because of the evolution complexity of Struts, we would have to first go through the Struts history with core focus on the versions. According to the Struts version that you use in your application, the integration methodology changes accordingly.

Struts were originally developed by the programmer and author Craig R. McClanahan and were later taken over by the Apache Software Foundation in 2002. Strut1 with all standard Java technologies and packages of Jakarta assists to create an extensible development environment. However, with the growing demand of web application, Struts 1 does not stand firm and needs to be changed with demand. This leads to the creation of Struts 2, which is more developer friendly with features like Ajax, rapid development and extensibility.

The team of Apache Struts and another J2EE framework, WebWork from OpenSymphony joined hand together to develop an advanced framework with all possible developing features that will make it developer and user friendly.

Even though the new version is Spring 2, we would still cover integration of Spring with Struts 1 as well so that if existing Struts 1 project needs the various capabilities of Spring, they can do so without much hassle.

Page Visitors: 5280

Spring Integration Vs. Apache Camel

The debate on which integration technology to use namely Spring Integration versus Apache Camel is one of the prominent topic now a days similar to mobile web application versus native mobile apps.

I don’t have any bias towards either Camel or Spring but for judgmental reasons I wanted to know which one to choose when given a chance in one of my projects. While doing so I did good amount of net surfing, and this blog post is an effort from my end to consolidate all the points that I could see in the internet. I have indeed plagiarized certain very good points from various blogs while doing so and some of the prominent blogs I have given as reference. Over the course of time I will be updating the blog post with more details as and when I find time.

Note: – I still haven’t been able to find an answer to my question and I am still using both co-jointly in my application. When using a connector I still don’t have a clear picture whether to use Spring connector or Camel connector.

Apache Camel – is a powerful open source integration framework based on known Enterprise Integration Patterns.

Spring Integration – It provides an extension to the Spring Framework to support the well-known Enterprise Integration Patterns while using the principles of Spring programming model.

Apache Camel as well as Spring Integration provides a lightweight alternative to ESB (Enterprise Service Bus), focusing on the programming model in such a way that the developer spends less time with infrastructural boilerplate.

 

 


Comparison from ohloh.net for the two projects:-

  • Camel has a total connector counts of >130 in all which does outscore Spring Integration by a great deal with Spring Integration catching up with every release. +1 Camel
  • Both are using Apache License version 2.0 which states, you can do whatever you want with the code. +1 Camel +1 Spring Integration.
  • Both projects have good activity with good amount of commits from good amount of committers. Camel does have an edge though over the number of commits with respect to Spring Integration. +1 Camel
  • Both started in the year 2007. The effort put for building Camel outscores Spring Integration by large. The lines of code with respect to Camel also outscore Spring Integration by a large distance. +1 Camel for the features it has with respect to lines of code. +1 Spring Integration as code lines cannot be said as a plus point (sometimes less code can be more effective and non-buggy).
  • Vibrant response community of Camel does outscore Spring Integration by a great deal. Might be because of Camel’s focused approach on integration as opposed to Spring’s all in one approach. What it means that most of the problems you face using Camel can be solved quickly by Googling as opposed to Spring Integration. Also the amount of stuff available in the case of Camel does outscore Spring Integration by a great deal as well. + Camel
  • JIRA activity is healthy in the case of Camel as opposed to Spring Integration. Again I see this because of the focused approach of Camel as well as attributed to the vibrant community along with good amount of code lines as compared to Spring Integration. Healthy JIRA activity does mean that turnaround time for a bug is quick in the case of Camel as compared to Spring Integration. +1 Camel
  • CamelOne conference for Camel and none for Spring Integration. Again this can be attributed to non-focus nature of Spring Framework as a whole as compared to Camel. +1 Camel
  • Both has good amount of tooling support in the form of STS and Fuse IDE. +1 Camel +1 Spring Integration
  • Both have commercial support and good amount of 3rd party consultants who are ready to help if you have more money to shell. +1 Camel +1 Spring Integration
  • Camel supports other DSL’s (Domain Specification Language) to a greater extend as compared with Spring Integration (ease of use and learn). +1 Camel

There is a very good presentation from Kai Wähner (Twitter: @KaiWaehner), which he presented in CamelOne Conference 2012, which does cover good amount of points and below is the slideshare details which he has shared. A well-documented comparison between various integration options available today on the Java (JVM) Platform. The author has played it safe similar to me by not giving a final verdict, but it will definitely help you to take into considerations and according to your application requirement take a right choice.

Some conclusions which can help the final decision:-

  • If you already have a Spring application which requires an integration layer, definitely Spring Integration is a good choice to make. If you have a non-spring application, using/introducing Camel as the integration layer would be really the way to go.

I don’t want to take any credit away from authors who has taken pain in doing this research. That’s the reason I would like to put the reference as the first section in my blog. I have gone through various blogs, tutorials and then compiled a blog in a focused and easy to understand manner.

References

http://www.ofbizian.com/2012/12/spring-integration-22-is-out-it-is-time.html

One of the post from Mark Fisher will surely give an insight into the reason behind developing Spring Integration – http://www.coderanch.com/t/568364/Spring/Camel-Spring-Integration-Part

http://www.kai-waehner.de/blog/2012/01/10/spoilt-for-choice-which-integration-framework-to-use-spring-integration-mule-esb-or-apache-camel/

Page Visitors: 6060

Spring Book – Chapter 11 – Spring Web

Large number of enterprise web applications is developed using Java and forms a very integral part of any organization in modern day. Web applications have become more and more complex and it poses more and more challenges day by day. Having a good web framework should be able to address most of these challenges there by reducing the effort on the developer and allowing them to focus on implementation of actual business logic.

This Chapter introduces you to the Spring Frameworks web support and the various components in the Spring web stack. This is just an introduction to the Spring’s frameworks role in the web application development support.

The Chapter starts off by explaining the Spring web stack and the various components which it comprises. Later on it delves deep into each component and explains each one in detail. Following with the Spring philosophy it then covers the various integration possible with your Spring application. Since some integration is really important, these are covered as separate chapters later on.

A Little History

Before going deep into the Spring web stack, a little history about the Spring web stack development from its early days to present.

Spring started its journey in 2002 and Spring Web was part of the original Spring ecosystem and contained servlet/web tier tool for aiding web application development. Then came Spring Frameworks own MVC framework in the form of Spring MVC. Following the core principles of Spring, it allowed to integrate with other frameworks.

Then came the inclusion of Spring Portlet MVC which was contributed initially by Rutgers in April 2004. John Lewis started contributing changes and it got included in the main Spring code base along with Spring 2.0 release.

Spring Web Flow started as a sub project and its first release was in March 2005. Due to its innovative ideas and good acceptability in the industry after inception, it soon became an independent project and got its independent release version 1.0 released in the same year.

Over the period Spring MVC and Spring Web Flow evolved and is considered among the renounced web technology stack.

Spring Web Stack

Modern day web application posses high level of challenges, including the following:

  • Complexity continues to rise at an alarming rate
  • Necessity of exposing services to a larger audience
  • Ability to give users the best possible experience in the shortest possible of time
  • High expectations
  • Ability to build simpler applications
  • Cloud enablement

Ideally any web framework chosen for web application development should address the above challenges reducing much of the complexity for the developer. Spring provides a full stack web framework by gathering multiple libraries and frameworks useful for web development into a single unified software stack for web developers to use. It tries to address the rising complexities raised by web application development by building on top of the lightweight Spring container. Figure 11-1 shows the various components provided by the Spring web stack for developing web application using this foundation.

Figure 11-1. Spring Web Stack components

The Spring Web Stack gives you:

  • A unified programming model
  • Capability to handle multiple client types using the same foundation
  • Adaptability to choose the right approach according to the required use case

The various Spring web stack components are:

  • Spring Framework and Spring MVC
  • Spring Web Flow
  • Spring Security
  • Spring JavaScript
  • Spring Faces
  • Spring BlazeDS Integration

Page Visitors: 2137

Spring Book – Part III – Web Application Development Support by Spring

For any organization, business applications based on web has become a sort of mandate due to its evolvement over the period of time. Spring Framework provides modules which aids in developing web application infrastructure for the server side.

This part of the book contains Chapters which will help you in developing web application with the help of Spring Framework. More importantly it lets the reader understand the web application development support by the Spring Framework.

Chapter 11, “Spring Web”, introduces you to the Spring web stack as a whole. It introduces you to various components in the Spring web stack and also covers some basics around Spring web and other web technology facts like MVC framework and so forth.

Chapter 12, “Spring and Struts Integration”, purely looks into the integration of Spring Framework with the famous MVC framework, Struts in detail.

Chapter 13, “Spring and JSF Integration”, similar to Chapter 12, looks at integrating Spring Framework with another famous MVC framework Java Server Faces (JSF) in detail.

Chapter 14, “Spring MVC and Spring Web Flow”, goes into detail of Spring MVC, Spring Frameworks implementation of MVC pattern and Spring Web Flow in detail.

Chapter 15, “Web Application Security with Spring”, covers the most important aspect of any enterprise application, security. It covers Spring Security in detail with respect to web application security.

Chapter 11: Spring Web

Chapter 12: Spring and Struts Integration

Chapter 13: Spring and JSF Integration

Chapter 14: Spring MVC and Spring Web Flow

Chapter 15: Web Application Security with Spring

Page Visitors: 267

Spring Book – Chapter 10 – Caching

Cache is a component that transparently stores data so that future requests for that data can be served faster. The data that is stored within a cache might be values that have been computed earlier or duplicates of original values that are stored elsewhere. If requested data is contained in the cache (cache hit), this request can be served by simply reading the cache, which is comparatively faster. Otherwise (cache miss), the data has to be recomputed or fetched from its original storage location, which is comparatively slower. Hence, the greater the number of requests that can be served from the cache, the faster the overall system performance becomes.

–          wikipedia.org

“Cache” is a specialized form of computer memory.

–          About.com

A cache stores recently-used information in a place where it can be accessed extremely fast.

–          techterms.com

 To store data locally in order to speed up subsequent retrievals.

–          pcmag.com

One of the new features added in Spring Framework in its version 3.1 is its support for transparently adding caching into an existing Spring application. Similar to transaction management, it allows developers to incorporate consistent use of various caching solution available in market with minimal or no impact on the source code.

In this chapter we will first go through various caching concepts and why it should be used in your application. We will then delve deep into as to how we can do this in your Spring application. In these sections we will cover the various nitty-gritties involved in configuring caching for your application. We will also see Spring’s support for other third party cache libraries available today and then finally wrap the chapter with the concept of distributed caches to some extent.

After reading this chapter you should have a clear idea of the cache abstraction provided by the Spring framework and also have a very clear idea of using caching in your existing and new application build on Spring Framework.

Why Caching?

Caching has been one of the methods employed to speed up an application and relieve its workload. Its usefulness is particularly apparent today with the rise of social web applications, visited by thousands of people at the same time. Moreover caching should be something orthogonal, having minimal or nil side-effects to the business logic that a developer writes. There are many cache libraries in Java world, both commercial and open source.

Caching is an essential tool for scaling web applications. It avoid disk access, I/O, CPU power and network traffic – primarily to the backend relational database in modern web applications.


Application without Caching Layer

An application that doesn’t have a caching layer has the following  known problems:

  • Every call creates new objects in CPU memory and Java heap.
  • Duplicate objects in Java heap due to repeated database calls.
  • All data comes from database which involves network call and is very expensive in nature.
  • Due to network involvement in various steps in the overall execution, response times get affected.
  • A single call might in turn call multiple data sources to get all required data, in which case it becomes more expensive and more time consuming.
  • Due to high amount of objects in Java heap, it could trigger Java garbage collection which is very expensive.
  • There is an additional requirement of CPU in doing the marshalling of data from database to the format required in the application layer.

Figure 10-1 shows a typical application without caching layer. It shows applications interacting with more than one data source to retrieve all the required data in your application. It also shows interaction of application directly with various data sources which are very expensive and also time intensive.

Figure 10-1. Application interactions without caching layer

Page Visitors: 11432

Spring Book – Chapter 9 – Transaction Management

The concept of transaction is essential to any business application. A transaction, in layman’s term, makes sure that only contracted-upon, dependable, and satisfactory state changes are made to a system, regardless of any failure in the system or issues arising due to concurrent access to the system’s resources.

The present application architectures brings along with it lot of complexities, having veracious systems joined together achieving a business case into reality. This brings along challenges to existing transaction models, which application frameworks keep on innovating to achieve it. Spring provides excellent transaction management capabilities considering modern day application’s transaction requirement and complexities.

The initial sections of this chapter deal with fundamental concepts in and around transactions in general. Later sections concentrate on how Spring comes into picture to address these transaction concepts.

Why Transactions?

In simple terms transaction can be thought of as an interaction with a system resulting in a state change of the system. It is a common practice to mention transaction as a “unit of work”.  In most of the cases, these interactions can be successful, but any number of unforeseen events can interrupt this interaction, leaving the system in an incomplete, inconsistent and unstable form which is not good for the overall application system.

By putting the interaction with the system inside a transaction boundary, you get a guarantee that the interaction is achieved successfully, and in case if it is not, it keeps the system in consistent and stable form.

In simpler terms, in reality, any application is bound to fail at some point in its life. This might result from programming problems, loss of power supply, hardware issues, incorrect input data, user error and so forth. The causes are many, but the end result is same; you application in an inconsistent manner. Putting your interaction with the application inside a transaction boundary can mitigate it to some extend and this is the reason you should use transaction in your application.


ACID Transactions

In any modern day applications, transactions are required to satisfy the so called ACID properties, that is, the set of operations involved in a transaction should occur atomically, should be consistent, should be isolated from other operations, and their effects should be durable in time. We will explain each of the following properties:

  • Atomicity
  • Consistency
  • Isolation
  • Durability

Atomicity

It is the property of a transaction to either complete successfully or not at all in the event of complete or partial failure. All the activities within a particular transaction should be indivisible, that is, atomic in nature.

Consistency

It is the property of a transaction to begin and end in a state which is consistent and not breaking any integrity constraints. A database or other persistent store defines referential and entity integrity rules to ensure that data in the store is consistent at all times. A transaction that changes the data must ensure that the data remains in a consistent state and that data integrity rules are not violated, regardless of whether the transaction is a success or failure. The data in the store may not be consistent during the duration of the transaction, but the inconsistency is invisible to other transactions, and consistency must be restored when the transaction completes.

Isolation

It is the property of a transaction to perform operations isolated from all other operations in a particular application. One transaction should not see other transaction’s data in an intermediate state at any stage. When multiple transactions are in progress, one transaction may want to read the same data another transaction has changed but not committed. Up until the transaction commits, the changes made by it should be treated as transient state, because the transaction could roll back the change. If other transactions read intermediate or transient states caused by a transaction in progress, additional application logic must be executed to handle the effects of some transactions having read potentially erroneous data. This property tells how concurrent transaction should behave in which it actions on same set of data in an application.

There are various isolation levels which exist in the case of transaction, which will be covered in later sections of this chapter.

Durability

It is the property of a transaction wherein, state changes made within a transactional boundary in an application must be persisted onto permanent storage media, such as disks, databases, or file systems. If due to any reason application fails after the transaction has committed, the system should guarantee that the effects of the transaction will be visible to the application when it restarts. Any change committed by one transaction must be durable until another valid transaction changes the data.

Transaction Types

There are various means by which a transaction is classified into different types. Some of the well-known transaction type terminology is explained below so that you have a clear idea when these are used at various stages of this chapter.

Local Transactions

Transactions that deal with just one resource such as one database are known as local transactions. Coding using local transactions can be easier but has significant disadvantages attached to it. They are:

  • It cannot work with multiple transactional resources.
  • Invasive/disturbing to the underlying programming model.

Global/Distributed Transactions

Transactions that span multiple resources such as more than one database or a database and a messaging engine are called global transactions. They too have advantages attached to it, which can be summarized as below:

  • The application server manages global transactions using JTA (Java Transaction API), which can be cumbersome API to use.
  • Usually, JTA in an application server is sourced from JNDI, which indirectly brings in dependency of JNDI to your application.

Spring addresses disadvantage of both local and global transactions alike, by addressing these disadvantages, as well as introducing its own unique advantages which are covered in the section named “Advantages of Spring Transaction Management” below.

Note: For Java Standard Environment, stand-alone JTA implementations can be wired to use the Spring’s JtaTransactionManager, which is covered in the following sections of this chapter. This way Spring addresses both the disadvantages mentioned in the above section.

Page Visitors: 7964