Tag Archives: Spring Framework

Spring Framework Vs. JEE – Part II

As promised this is my second part of my blog. The first part of the blog can be accessed from here.

As part writing this blog i browsed through various blogs on the same topic. As i told in my first blog, this really is a holy war and over coming few months and years, this will rage even harder.

I bust out into laugh after reading one of the blogs, the link for which is as given below:-

http://broadleaf.tumblr.com/post/31333966305/broadleaf-continues-to-choose-spring-framework

The point that i burst outlaughing when the author stated as below:-

<quote>

…… Java EE 5 took a few pages out of Spring’s book and simplified the development of enterprise components with…….

</quote>

Yes, JEE sure did take some very crucial and important pages out of Spring book and because of which it is becoming superior day-by-day if not by huge margin. Spring with full support from its community is not far behind and with foundation in place, its building up components one after another. Its also adding in more and more support for open source libraries with ever growing sub-projects under the Spring Framework umbrella.

Also now its is slowly becoming a norm when considering a new open source for development to see how strongly it can be integrated into Spring and how seamless Spring configurations can be used. In my web service framework comparison, you wouldn’t believe, this was considered as one of the requirements and it will be a bonus for any open source to state that “they can be integrated into Spring” with some few lines of Java or XML configuration.

Spring has an edge by keeping it open for good open source libraries to plug on at any time and replace these libraries with a new one by mere configurations (at-least theoretically possible… :)). Java theoretically is “Write once run anywhere”, but is it truly that easy for a a production application to move from one environment to a new one… Hmmm… I don’t think so… 🙂

I am sort of exhausted already writing this blog. I will have to put you all in some suspense and put everything else that i plan to write in a new blog part. Hold on tight and i am sure i wouldn’t make you unhappy. Expect third part in another 3 days time. Its weekend here and i am really looking forward to it in a big way.

Page Visitors: 379

Spring Framework Vs. JEE – Part I

Am I playing with fire here. Perhaps Yes.

As many say, this truly classify itself to be a holy war for predominance and will surely stir some dirty stuff out into the air.

One of my colleagues recently came to me and had a small debate as to why the our organization selected Spring over JEE. He was very much in favor of JEE especially JEE 6.

We sometime back (more than an year) had an exercise in which the task was to choose organization wide Java framework. As you guessed right, we did have Spring Framework and JEE as strong candidates. Our approach was really methodical and a methodology which was devised internal to the organization was used.

In this methodology the two candidates was put into test. First of all, various architecture quality attributes were put in such as Performance, Scalability, Testability etc. and then various requirements in these attributes were classified/grouped together. Once we have that, we get the various stakeholders involved and get their buy in and their stand on the overall acceptance of these quality attributes and rank it. We then went on with POC (Proof of Concept) and each requirement was rated against each of the chosen frameworks.

Finally after a grueling exercise of rating various requirement for each of the framework, a final rating comes out which give good indication as to which on quality attributes gets favored for each of the framework and according to the stakeholders, which one to choose out of these two. The choice was made and there was no surprise, it was Spring Framework.

For our company now the chosen default framework is Spring and anything else if it is taken, it goes as an exception.

For me when i say that i use Spring Framework, it doesn’t in any way mean that i don’t use JEE. They cannot be mutually exclusive, rather when combined together, it gives immense advantage to the project that you are developing. We do use Spring as our choice of framework but haven’t just taken out JEE in any sense out of the window, rather when the right time comes another evaluation as detailed above will be done to asses the situation even further. Till that time i feel choosing Spring as the default framework is a good one in all aspects.

In my next blog (Click here), I would try to give some of the major points, which made us choose Spring as a default framework of choice for developing any application within the organization.

Earlier i have done couple of comparisons as detailed below:-

Spring Integration Vs. Apache Camel

Web Service Framework Comparison – 2013 – Part I

Web Service Framework Comparison – 2013 – Part II

Page Visitors: 1054

Spring Book – Chapter 17 – Messaging with Spring

Messaging is a method of communication between software components or applications. Messaging enables distributed communication that is “loosely coupled” (decoupled). A component sends a message to a destination, and the recipient can retrieve the message from the destination. The important thing here is that, the sender and the receiver do not have to be available at the same time in order to communicate with each other.

Java Message Service (JMS) defines a standard way for Java applications to create and exchange messages through a Message Oriented Middleware (MOM).

Messaging is one of the key components in any modern day application development. In this Chapter we will initially cover messaging concepts in some detail. Later on we will cover JMS and its components in detail. We will then deep-dive into the support provided by Spring in applying messaging to your application. We will then go through the transaction support by JMS and again what Spring has to offer in this space. Finally, the Chapter concludes with a discussion of Spring’s support in achieving global transactions in your application.

Messaging in General

Messaging systems are used to build highly reliable, scalable, and flexible distributed applications. A messaging system allows separate, uncoupled applications to reliably do the communication asynchronously. The messaging system architecture generally replaces the client/server model with a peer-to-peer relationship between individual components, where each peer can send and receive messages to and from other peers.

Messaging systems provide a host of powerful advantages over other, more conventional distributed computing models. Primarily, they encourage “loose coupling” between message consumers and message producers. Other advantages of messaging systems include high scalability, easy integration with other heterogeneous networks, and reliability due to lack of a single point of failure.

Messaging is another integration style as detailed in Chapter 6.  Systems exchange messages within each other using a component known  as a broker, which provides the necessary guarantee and services while using messaging along with capability of interfacing with other interfaces like JMS driver, AMQP (Advanced Message Queuing Protocol), Stomp (Simple Text Oriented Message Protocol), XMPP (Extensible Messaging and Presence Protocol) etc. These interfaces are often referred to as Message Oriented Middleware (MOM) and are available as commercial and open source products in the market. Figure 18-1 shows a diagram of a MOM-based messaging system.

fig18-01

Figure 18-1. Messaging using MOM

Message-oriented middleware (MOM) is software or hardware infrastructure supporting sending and receiving messages between distributed systems. MOM allows application modules to be distributed over heterogeneous platforms and reduces the complexity of developing applications that span multiple operating systems and network protocols, such as the following:

  • Simple (or Streaming) Text Orientated Messaging Protocol (STOMP) provides an interoperable wire format so that STOMP clients can communicate with any STOMP message broker to provide easy and widespread messaging interoperability among many languages, platforms and brokers.
  • Advanced Message Queuing Protocol (AMQP) is an open standard application layer protocol for message-oriented middleware. It’s a binary, application layer protocol, designed to efficiently support a wide variety of messaging applications and communication patterns.
  • Extensible Messaging and Presence Protocol (XMPP) is an open-standard communications protocol for message-oriented middleware based on XML (Extensible Markup Language). The protocol was originally named Jabber, and was developed by the Jabber open-source community.

Advantages of Messaging

The main advantages of using messaging as an integration technology in your application can be summarized as below:

  • Platform Independence – one of the biggest advantages which messaging integration style brings onto table is communication and integration of heterogeneous platforms. Using messaging it is possible to integrate applications and systems which are implemented in completely different platforms. Even though we have many ways of integrating heterogeneous platforms like RPC-based, common database etc., only messaging truly provides a decoupled way of interaction between such disparate systems.
  • Network location Independence -messaging also provides capability of connections applications and systems in completely different networks with ease.
  • Architecture Flexibility and Agility – this very important advantage of messaging is achieved through level of abstraction and decoupling capabilities. Because of decoupled components, these can be replaced with a more capable component at a later stage with ease giving application flexibility and agility to changing business scenarios. In a typical messaging environment, the various components like producers, consumers and client components doesn’t need to know which programming language or platform these are written for, where they are located and even the protocol they used to communicate. These details are all abstracted away, making it more flexible from the architecture point of view.
  • Reduce system bottleneck – asynchronous nature of messaging is the key in avoiding system bottlenecks. Since messaging architecture gives your application asynchronous nature, your receivers need not keep up with the rate of requests coming in reducing the system bottlenecks. In a synchronous environment, your application would have resulted in system bottlenecks if the number of requests exceeds a particular amount which the consumer can consume and process.

Using traditional RPC-based technologies, there is a synchronous communication between a client and a server component. Also, communication between many to many can over a period of time turn into a mesh of one to one communication between various components as shown in Figure 18-2 below. This meshing can be troublesome from the application maintainability point of view.

Figure 18-2. Traditional RPC-based application component interaction

Figure 18-2. Traditional RPC-based application component interaction

On the other hand using a messaging style of integration allows adding a mediation layer between one or more consumers and one or more producers. This result in clear communication between various components which has a clear interface with other components interacts, making it easy to swap the various components according to application requirement. Figure 18-3 shows message-based component interaction.

Figure 18-3. Using messaging-based application component interaction

Figure 18-3. Using messaging-based application component interaction

Page Visitors: 16784

Spring Book – Chapter 16 – Web Services – Spring WS

In June 2000, Microsoft coined the term “Web Services” when they introduced this as one of the key component of its .NET framework. As other industry players started adopting this, it was evident that this technology would revolutionize distributed computing in the coming years. In the past few years many techniques have been developed to help applications interact with each other, of which prominent one is Web Services by a large extend.

Spring Web Services (Spring WS) follows the strategy of contract-first web services. It focuses more on XML and lesser on Java implementation. The underlying details are completely under the control of developers starting from the contract to the marshalling/unmarshalling details to the endpoint which actually handles the request.

Spring WS being a product of the Spring Framework, offers first class support of using Spring configurations and integrating with Spring framework. It provides ability to plug-in various XML APIs (SAX, DOM, StAX, XOM, and JDOM) to handle XML messages and can always ensure that the XML contract is marshaled correctly into Java objects. It supports JAXB 1 and 2, Castor, XMLBeans, JiBX, and XStream as part of its XML marshalling support.

When you have finished with this Chapter, you will have clear idea of all the terminologies related to web services and will also have a clear idea of the support provided by Spring to create and use web services in your application.

What is a Web Service

A Web service is a method of communication between two electronic devices over the Web (Internet).

– wikipedia.org

A Web service is a unit of managed code that can be remotely invoked using HTTP protocol which allows exposing the functionality of your existing code over the network which other application can use it.

To give you a better explanation of what a web service is, I would like to give you the exact working of web service pictorially shown in Figure 16-1 below.

fig16-01

Figure 16-1. Web service architecture

The various steps involved in actually consuming an already exposed web service can be summarized as below:

  1. The client (web service consumer), queries the UDDI registry to get the details of the service and to locate it in the network (Internet).
  2. The UDDI registry refers the web service requesting client to the WSDL document details.
  3. The requesting client accesses the WSDL document.
  4. The WSDL document gives all the relevant details of the requested web service to the client.
  5. The client now sends SOAP-message request to the actual web server exposing the service.
  6. The web service returns the SOAP-message response which the client receives and does the appropriate processing.

Concepts

Spring hides many of the web service complexities away from the developer. But since some concepts are very crucial in overall understanding of web services, we’ll take a brief look at some these concepts in the following sections.

SOAP Messages

SOAP (Simple Object Access Protocol) is an XML vocabulary that lets programs on separate computers interact across a network via RPC (Remote Procedure Call). A SOAP message can be of three types summarized as below:

  • Method call – it contains name of method and parameters.
  • Method Response -contains the return values.
  • Fault Message – if service throws exception, it produces SOAP fault message. Due to any reason if transport fails, it will give appropriate standard HTTP messages

The SOAP message structure is illustrated in Figure 16-2.

 Figure 16-2. A typical SOAP message structure

Figure 16-2. A typical SOAP message structure

Page Visitors: 11144

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: 6430

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: 13496

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: 9642